(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else if(typeof exports === 'object') exports["QdtComponents"] = factory(); else root["QdtComponents"] = factory(); })(window, function() { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "/"; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 129); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; if (true) { module.exports = __webpack_require__(82); } else {} /***/ }), /* 1 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ if (false) { var throwOnDirectAccess, ReactIs; } else { // By explicitly using `prop-types` you are opting into new production behavior. // http://fb.me/prop-types-in-prod module.exports = __webpack_require__(86)(); } /***/ }), /* 2 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return _extends; }); function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } /***/ }), /* 3 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony import */ var deepmerge__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(46); /* harmony import */ var deepmerge__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(deepmerge__WEBPACK_IMPORTED_MODULE_0__); var merge = function merge(x, y) { return deepmerge__WEBPACK_IMPORTED_MODULE_0___default()(x, y, { arrayMerge: function arrayMerge(destinationArray, sourceArray) { return sourceArray; } }); }; merge.all = function (arr) { return deepmerge__WEBPACK_IMPORTED_MODULE_0___default.a.all(arr, { arrayMerge: function arrayMerge(destinationArray, sourceArray) { return sourceArray; } }); }; /* harmony default export */ __webpack_exports__["a"] = (merge); /***/ }), /* 4 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; // CONCATENATED MODULE: ./node_modules/@material-ui/core/node_modules/@babel/runtime/helpers/esm/objectWithoutPropertiesLoose.js function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } // CONCATENATED MODULE: ./node_modules/@material-ui/core/node_modules/@babel/runtime/helpers/esm/objectWithoutProperties.js /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return _objectWithoutProperties; }); function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; } /***/ }), /* 5 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; function toVal(mix) { var k, y, str=''; if (mix) { if (typeof mix === 'object') { if (Array.isArray(mix)) { for (k=0; k < mix.length; k++) { if (mix[k] && (y = toVal(mix[k]))) { str && (str += ' '); str += y; } } } else { for (k in mix) { if (mix[k] && (y = toVal(k))) { str && (str += ' '); str += y; } } } } else if (typeof mix !== 'boolean' && !mix.call) { str && (str += ' '); str += mix; } } return str; } /* harmony default export */ __webpack_exports__["a"] = (function () { var i=0, x, str=''; while (i < arguments.length) { if (x = toVal(arguments[i++])) { str && (str += ' '); str += x } } return str; }); /***/ }), /* 6 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; // EXTERNAL MODULE: ./node_modules/@material-ui/core/node_modules/@babel/runtime/helpers/esm/extends.js var esm_extends = __webpack_require__(2); // EXTERNAL MODULE: ./node_modules/@material-ui/styles/node_modules/@babel/runtime/helpers/esm/extends.js var helpers_esm_extends = __webpack_require__(17); // EXTERNAL MODULE: ./node_modules/@material-ui/styles/node_modules/@babel/runtime/helpers/esm/objectWithoutProperties.js + 1 modules var objectWithoutProperties = __webpack_require__(24); // EXTERNAL MODULE: ./node_modules/react/index.js var react = __webpack_require__(0); var react_default = /*#__PURE__*/__webpack_require__.n(react); // EXTERNAL MODULE: ./node_modules/prop-types/index.js var prop_types = __webpack_require__(1); // EXTERNAL MODULE: ./node_modules/hoist-non-react-statics/dist/hoist-non-react-statics.cjs.js var hoist_non_react_statics_cjs = __webpack_require__(66); var hoist_non_react_statics_cjs_default = /*#__PURE__*/__webpack_require__.n(hoist_non_react_statics_cjs); // EXTERNAL MODULE: ./node_modules/@material-ui/styles/esm/makeStyles/makeStyles.js + 31 modules var makeStyles = __webpack_require__(157); // EXTERNAL MODULE: ./node_modules/@material-ui/styles/esm/getThemeProps/getThemeProps.js var getThemeProps = __webpack_require__(155); // EXTERNAL MODULE: ./node_modules/@material-ui/styles/esm/useTheme/useTheme.js var useTheme = __webpack_require__(154); // CONCATENATED MODULE: ./node_modules/@material-ui/styles/esm/withStyles/withStyles.js // Link a style sheet with a component. // It does not modify the component passed to it; // instead, it returns a new component, with a `classes` property. var withStyles_withStyles = function withStyles(stylesOrCreator) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; return function (Component) { var defaultTheme = options.defaultTheme, _options$withTheme = options.withTheme, withTheme = _options$withTheme === void 0 ? false : _options$withTheme, name = options.name, stylesOptions = Object(objectWithoutProperties["a" /* default */])(options, ["defaultTheme", "withTheme", "name"]); if (false) {} var classNamePrefix = name; if (false) { var displayName; } var useStyles = Object(makeStyles["a" /* default */])(stylesOrCreator, Object(helpers_esm_extends["a" /* default */])({ defaultTheme: defaultTheme, Component: Component, name: name || Component.displayName, classNamePrefix: classNamePrefix }, stylesOptions)); var WithStyles = react_default.a.forwardRef(function WithStyles(props, ref) { var classesProp = props.classes, innerRef = props.innerRef, other = Object(objectWithoutProperties["a" /* default */])(props, ["classes", "innerRef"]); var classes = useStyles(props); var theme; var more = other; if (typeof name === 'string' || withTheme) { // name and withTheme are invariant in the outer scope // eslint-disable-next-line react-hooks/rules-of-hooks theme = Object(useTheme["a" /* default */])() || defaultTheme; if (name) { more = Object(getThemeProps["a" /* default */])({ theme: theme, name: name, props: other }); } // Provide the theme to the wrapped component. // So we don't have to use the `withTheme()` Higher-order Component. if (withTheme && !more.theme) { more.theme = theme; } } return react_default.a.createElement(Component, Object(helpers_esm_extends["a" /* default */])({ ref: innerRef || ref, classes: classes }, more)); }); false ? undefined : void 0; // The wrapper receives only user supplied props, which could be a subset of // the actual props Component might receive due to merging with defaultProps. // So copying it here would give us the same result in the wrapper as well. WithStyles.defaultProps = Component.defaultProps; if (false) {} hoist_non_react_statics_cjs_default()(WithStyles, Component); if (false) {} return WithStyles; }; }; /* harmony default export */ var esm_withStyles_withStyles = (withStyles_withStyles); // EXTERNAL MODULE: ./node_modules/@material-ui/core/esm/styles/defaultTheme.js var styles_defaultTheme = __webpack_require__(26); // CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/styles/withStyles.js function styles_withStyles_withStyles(stylesOrCreator, options) { return esm_withStyles_withStyles(stylesOrCreator, Object(esm_extends["a" /* default */])({ defaultTheme: styles_defaultTheme["a" /* default */] }, options)); } /* harmony default export */ var styles_withStyles = __webpack_exports__["a"] = (styles_withStyles_withStyles); /***/ }), /* 7 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return capitalize; }); // It should to be noted that this function isn't equivalent to `text-transform: capitalize`. // // A strict capitalization should uppercase the first letter of each word a the sentence. // We only handle the first word. function capitalize(string) { if (false) {} return string.charAt(0).toUpperCase() + string.slice(1); } /***/ }), /* 8 */ /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__(88); /***/ }), /* 9 */ /***/ (function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! Copyright (c) 2017 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/classnames */ /* global define */ (function () { 'use strict'; var hasOwn = {}.hasOwnProperty; function classNames () { var classes = []; for (var i = 0; i < arguments.length; i++) { var arg = arguments[i]; if (!arg) continue; var argType = typeof arg; if (argType === 'string' || argType === 'number') { classes.push(arg); } else if (Array.isArray(arg) && arg.length) { var inner = classNames.apply(null, arg); if (inner) { classes.push(inner); } } else if (argType === 'object') { for (var key in arg) { if (hasOwn.call(arg, key) && arg[key]) { classes.push(key); } } } } return classes.join(' '); } if ( true && module.exports) { classNames.default = classNames; module.exports = classNames; } else if (true) { // register as 'classnames', consistent with npm package name !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = (function () { return classNames; }).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else {} }()); /***/ }), /* 10 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; function checkDCE() { /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */ if ( typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined' || typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE !== 'function' ) { return; } if (false) {} try { // Verify that the code above has been dead code eliminated (DCE'd). __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(checkDCE); } catch (err) { // DevTools shouldn't crash React, no matter what. // We should still report in case we break this code. console.error(err); } } if (true) { // DCE check should happen before ReactDOM bundle executes so that // DevTools can report bad minification during injection. checkDCE(); module.exports = __webpack_require__(83); } else {} /***/ }), /* 11 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* unused harmony export hexToRgb */ /* unused harmony export rgbToHex */ /* unused harmony export hslToRgb */ /* unused harmony export decomposeColor */ /* unused harmony export recomposeColor */ /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return getContrastRatio; }); /* unused harmony export getLuminance */ /* unused harmony export emphasize */ /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return fade; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return darken; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return lighten; }); /* eslint-disable no-use-before-define */ /** * Returns a number whose value is limited to the given range. * * @param {number} value The value to be clamped * @param {number} min The lower boundary of the output range * @param {number} max The upper boundary of the output range * @returns {number} A number in the range [min, max] */ function clamp(value) { var min = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; var max = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1; if (false) {} return Math.min(Math.max(min, value), max); } /** * Converts a color from CSS hex format to CSS rgb format. * * @param {string} color - Hex color, i.e. #nnn or #nnnnnn * @returns {string} A CSS rgb color string */ function hexToRgb(color) { color = color.substr(1); var re = new RegExp(".{1,".concat(color.length / 3, "}"), 'g'); var colors = color.match(re); if (colors && colors[0].length === 1) { colors = colors.map(function (n) { return n + n; }); } return colors ? "rgb(".concat(colors.map(function (n) { return parseInt(n, 16); }).join(', '), ")") : ''; } function intToHex(int) { var hex = int.toString(16); return hex.length === 1 ? "0".concat(hex) : hex; } /** * Converts a color from CSS rgb format to CSS hex format. * * @param {string} color - RGB color, i.e. rgb(n, n, n) * @returns {string} A CSS rgb color string, i.e. #nnnnnn */ function rgbToHex(color) { // Idempotent if (color.indexOf('#') === 0) { return color; } var _decomposeColor = decomposeColor(color), values = _decomposeColor.values; return "#".concat(values.map(function (n) { return intToHex(n); }).join('')); } /** * Converts a color from hsl format to rgb format. * * @param {string} color - HSL color values * @returns {string} rgb color values */ function hslToRgb(color) { color = decomposeColor(color); var _color = color, values = _color.values; var h = values[0]; var s = values[1] / 100; var l = values[2] / 100; var a = s * Math.min(l, 1 - l); var f = function f(n) { var k = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : (n + h / 30) % 12; return l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1); }; var type = 'rgb'; var rgb = [Math.round(f(0) * 255), Math.round(f(8) * 255), Math.round(f(4) * 255)]; if (color.type === 'hsla') { type += 'a'; rgb.push(values[3]); } return recomposeColor({ type: type, values: rgb }); } /** * Returns an object with the type and values of a color. * * Note: Does not support rgb % values. * * @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla() * @returns {object} - A MUI color object: {type: string, values: number[]} */ function decomposeColor(color) { // Idempotent if (color.type) { return color; } if (color.charAt(0) === '#') { return decomposeColor(hexToRgb(color)); } var marker = color.indexOf('('); var type = color.substring(0, marker); if (['rgb', 'rgba', 'hsl', 'hsla'].indexOf(type) === -1) { throw new Error(["Material-UI: unsupported `".concat(color, "` color."), 'We support the following formats: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla().'].join('\n')); } var values = color.substring(marker + 1, color.length - 1).split(','); values = values.map(function (value) { return parseFloat(value); }); return { type: type, values: values }; } /** * Converts a color object with type and values to a string. * * @param {object} color - Decomposed color * @param {string} color.type - One of: 'rgb', 'rgba', 'hsl', 'hsla' * @param {array} color.values - [n,n,n] or [n,n,n,n] * @returns {string} A CSS color string */ function recomposeColor(color) { var type = color.type; var values = color.values; if (type.indexOf('rgb') !== -1) { // Only convert the first 3 values to int (i.e. not alpha) values = values.map(function (n, i) { return i < 3 ? parseInt(n, 10) : n; }); } else if (type.indexOf('hsl') !== -1) { values[1] = "".concat(values[1], "%"); values[2] = "".concat(values[2], "%"); } return "".concat(type, "(").concat(values.join(', '), ")"); } /** * Calculates the contrast ratio between two colors. * * Formula: https://www.w3.org/TR/WCAG20-TECHS/G17.html#G17-tests * * @param {string} foreground - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla() * @param {string} background - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla() * @returns {number} A contrast ratio value in the range 0 - 21. */ function getContrastRatio(foreground, background) { var lumA = getLuminance(foreground); var lumB = getLuminance(background); return (Math.max(lumA, lumB) + 0.05) / (Math.min(lumA, lumB) + 0.05); } /** * The relative brightness of any point in a color space, * normalized to 0 for darkest black and 1 for lightest white. * * Formula: https://www.w3.org/TR/WCAG20-TECHS/G17.html#G17-tests * * @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla() * @returns {number} The relative brightness of the color in the range 0 - 1 */ function getLuminance(color) { color = decomposeColor(color); var rgb = color.type === 'hsl' ? decomposeColor(hslToRgb(color)).values : color.values; rgb = rgb.map(function (val) { val /= 255; // normalized return val <= 0.03928 ? val / 12.92 : Math.pow((val + 0.055) / 1.055, 2.4); }); // Truncate at 3 digits return Number((0.2126 * rgb[0] + 0.7152 * rgb[1] + 0.0722 * rgb[2]).toFixed(3)); } /** * Darken or lighten a color, depending on its luminance. * Light colors are darkened, dark colors are lightened. * * @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla() * @param {number} coefficient=0.15 - multiplier in the range 0 - 1 * @returns {string} A CSS color string. Hex input values are returned as rgb */ function emphasize(color) { var coefficient = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0.15; return getLuminance(color) > 0.5 ? darken(color, coefficient) : lighten(color, coefficient); } /** * Set the absolute transparency of a color. * Any existing alpha values are overwritten. * * @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla() * @param {number} value - value to set the alpha channel to in the range 0 -1 * @returns {string} A CSS color string. Hex input values are returned as rgb */ function fade(color, value) { color = decomposeColor(color); value = clamp(value); if (color.type === 'rgb' || color.type === 'hsl') { color.type += 'a'; } color.values[3] = value; return recomposeColor(color); } /** * Darkens a color. * * @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla() * @param {number} coefficient - multiplier in the range 0 - 1 * @returns {string} A CSS color string. Hex input values are returned as rgb */ function darken(color, coefficient) { color = decomposeColor(color); coefficient = clamp(coefficient); if (color.type.indexOf('hsl') !== -1) { color.values[2] *= 1 - coefficient; } else if (color.type.indexOf('rgb') !== -1) { for (var i = 0; i < 3; i += 1) { color.values[i] *= 1 - coefficient; } } return recomposeColor(color); } /** * Lightens a color. * * @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla() * @param {number} coefficient - multiplier in the range 0 - 1 * @returns {string} A CSS color string. Hex input values are returned as rgb */ function lighten(color, coefficient) { color = decomposeColor(color); coefficient = clamp(coefficient); if (color.type.indexOf('hsl') !== -1) { color.values[2] += (100 - color.values[2]) * coefficient; } else if (color.type.indexOf('rgb') !== -1) { for (var i = 0; i < 3; i += 1) { color.values[i] += (255 - color.values[i]) * coefficient; } } return recomposeColor(color); } /***/ }), /* 12 */ /***/ (function(module, exports, __webpack_require__) { (function (global, factory) { true ? factory(exports) : undefined; }(this, (function (exports) { 'use strict'; // Polyfills if ( Number.EPSILON === undefined ) { Number.EPSILON = Math.pow( 2, - 52 ); } if ( Number.isInteger === undefined ) { // Missing in IE // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger Number.isInteger = function ( value ) { return typeof value === 'number' && isFinite( value ) && Math.floor( value ) === value; }; } // if ( Math.sign === undefined ) { // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign Math.sign = function ( x ) { return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : + x; }; } if ( 'name' in Function.prototype === false ) { // Missing in IE // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name Object.defineProperty( Function.prototype, 'name', { get: function () { return this.toString().match( /^\s*function\s*([^\(\s]*)/ )[ 1 ]; } } ); } if ( Object.assign === undefined ) { // Missing in IE // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign Object.assign = function ( target ) { if ( target === undefined || target === null ) { throw new TypeError( 'Cannot convert undefined or null to object' ); } var output = Object( target ); for ( var index = 1; index < arguments.length; index ++ ) { var source = arguments[ index ]; if ( source !== undefined && source !== null ) { for ( var nextKey in source ) { if ( Object.prototype.hasOwnProperty.call( source, nextKey ) ) { output[ nextKey ] = source[ nextKey ]; } } } } return output; }; } var REVISION = '113'; var MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 }; var TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 }; var CullFaceNone = 0; var CullFaceBack = 1; var CullFaceFront = 2; var CullFaceFrontBack = 3; var FrontFaceDirectionCW = 0; var FrontFaceDirectionCCW = 1; var BasicShadowMap = 0; var PCFShadowMap = 1; var PCFSoftShadowMap = 2; var VSMShadowMap = 3; var FrontSide = 0; var BackSide = 1; var DoubleSide = 2; var FlatShading = 1; var SmoothShading = 2; var NoColors = 0; var FaceColors = 1; var VertexColors = 2; var NoBlending = 0; var NormalBlending = 1; var AdditiveBlending = 2; var SubtractiveBlending = 3; var MultiplyBlending = 4; var CustomBlending = 5; var AddEquation = 100; var SubtractEquation = 101; var ReverseSubtractEquation = 102; var MinEquation = 103; var MaxEquation = 104; var ZeroFactor = 200; var OneFactor = 201; var SrcColorFactor = 202; var OneMinusSrcColorFactor = 203; var SrcAlphaFactor = 204; var OneMinusSrcAlphaFactor = 205; var DstAlphaFactor = 206; var OneMinusDstAlphaFactor = 207; var DstColorFactor = 208; var OneMinusDstColorFactor = 209; var SrcAlphaSaturateFactor = 210; var NeverDepth = 0; var AlwaysDepth = 1; var LessDepth = 2; var LessEqualDepth = 3; var EqualDepth = 4; var GreaterEqualDepth = 5; var GreaterDepth = 6; var NotEqualDepth = 7; var MultiplyOperation = 0; var MixOperation = 1; var AddOperation = 2; var NoToneMapping = 0; var LinearToneMapping = 1; var ReinhardToneMapping = 2; var Uncharted2ToneMapping = 3; var CineonToneMapping = 4; var ACESFilmicToneMapping = 5; var UVMapping = 300; var CubeReflectionMapping = 301; var CubeRefractionMapping = 302; var EquirectangularReflectionMapping = 303; var EquirectangularRefractionMapping = 304; var SphericalReflectionMapping = 305; var CubeUVReflectionMapping = 306; var CubeUVRefractionMapping = 307; var RepeatWrapping = 1000; var ClampToEdgeWrapping = 1001; var MirroredRepeatWrapping = 1002; var NearestFilter = 1003; var NearestMipmapNearestFilter = 1004; var NearestMipMapNearestFilter = 1004; var NearestMipmapLinearFilter = 1005; var NearestMipMapLinearFilter = 1005; var LinearFilter = 1006; var LinearMipmapNearestFilter = 1007; var LinearMipMapNearestFilter = 1007; var LinearMipmapLinearFilter = 1008; var LinearMipMapLinearFilter = 1008; var UnsignedByteType = 1009; var ByteType = 1010; var ShortType = 1011; var UnsignedShortType = 1012; var IntType = 1013; var UnsignedIntType = 1014; var FloatType = 1015; var HalfFloatType = 1016; var UnsignedShort4444Type = 1017; var UnsignedShort5551Type = 1018; var UnsignedShort565Type = 1019; var UnsignedInt248Type = 1020; var AlphaFormat = 1021; var RGBFormat = 1022; var RGBAFormat = 1023; var LuminanceFormat = 1024; var LuminanceAlphaFormat = 1025; var RGBEFormat = RGBAFormat; var DepthFormat = 1026; var DepthStencilFormat = 1027; var RedFormat = 1028; var RedIntegerFormat = 1029; var RGFormat = 1030; var RGIntegerFormat = 1031; var RGBIntegerFormat = 1032; var RGBAIntegerFormat = 1033; var RGB_S3TC_DXT1_Format = 33776; var RGBA_S3TC_DXT1_Format = 33777; var RGBA_S3TC_DXT3_Format = 33778; var RGBA_S3TC_DXT5_Format = 33779; var RGB_PVRTC_4BPPV1_Format = 35840; var RGB_PVRTC_2BPPV1_Format = 35841; var RGBA_PVRTC_4BPPV1_Format = 35842; var RGBA_PVRTC_2BPPV1_Format = 35843; var RGB_ETC1_Format = 36196; var RGBA_ASTC_4x4_Format = 37808; var RGBA_ASTC_5x4_Format = 37809; var RGBA_ASTC_5x5_Format = 37810; var RGBA_ASTC_6x5_Format = 37811; var RGBA_ASTC_6x6_Format = 37812; var RGBA_ASTC_8x5_Format = 37813; var RGBA_ASTC_8x6_Format = 37814; var RGBA_ASTC_8x8_Format = 37815; var RGBA_ASTC_10x5_Format = 37816; var RGBA_ASTC_10x6_Format = 37817; var RGBA_ASTC_10x8_Format = 37818; var RGBA_ASTC_10x10_Format = 37819; var RGBA_ASTC_12x10_Format = 37820; var RGBA_ASTC_12x12_Format = 37821; var LoopOnce = 2200; var LoopRepeat = 2201; var LoopPingPong = 2202; var InterpolateDiscrete = 2300; var InterpolateLinear = 2301; var InterpolateSmooth = 2302; var ZeroCurvatureEnding = 2400; var ZeroSlopeEnding = 2401; var WrapAroundEnding = 2402; var TrianglesDrawMode = 0; var TriangleStripDrawMode = 1; var TriangleFanDrawMode = 2; var LinearEncoding = 3000; var sRGBEncoding = 3001; var GammaEncoding = 3007; var RGBEEncoding = 3002; var LogLuvEncoding = 3003; var RGBM7Encoding = 3004; var RGBM16Encoding = 3005; var RGBDEncoding = 3006; var BasicDepthPacking = 3200; var RGBADepthPacking = 3201; var TangentSpaceNormalMap = 0; var ObjectSpaceNormalMap = 1; var ZeroStencilOp = 0; var KeepStencilOp = 7680; var ReplaceStencilOp = 7681; var IncrementStencilOp = 7682; var DecrementStencilOp = 7683; var IncrementWrapStencilOp = 34055; var DecrementWrapStencilOp = 34056; var InvertStencilOp = 5386; var NeverStencilFunc = 512; var LessStencilFunc = 513; var EqualStencilFunc = 514; var LessEqualStencilFunc = 515; var GreaterStencilFunc = 516; var NotEqualStencilFunc = 517; var GreaterEqualStencilFunc = 518; var AlwaysStencilFunc = 519; var StaticDrawUsage = 35044; var DynamicDrawUsage = 35048; var StreamDrawUsage = 35040; var StaticReadUsage = 35045; var DynamicReadUsage = 35049; var StreamReadUsage = 35041; var StaticCopyUsage = 35046; var DynamicCopyUsage = 35050; var StreamCopyUsage = 35042; /** * https://github.com/mrdoob/eventdispatcher.js/ */ function EventDispatcher() {} Object.assign( EventDispatcher.prototype, { addEventListener: function ( type, listener ) { if ( this._listeners === undefined ) { this._listeners = {}; } var listeners = this._listeners; if ( listeners[ type ] === undefined ) { listeners[ type ] = []; } if ( listeners[ type ].indexOf( listener ) === - 1 ) { listeners[ type ].push( listener ); } }, hasEventListener: function ( type, listener ) { if ( this._listeners === undefined ) { return false; } var listeners = this._listeners; return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1; }, removeEventListener: function ( type, listener ) { if ( this._listeners === undefined ) { return; } var listeners = this._listeners; var listenerArray = listeners[ type ]; if ( listenerArray !== undefined ) { var index = listenerArray.indexOf( listener ); if ( index !== - 1 ) { listenerArray.splice( index, 1 ); } } }, dispatchEvent: function ( event ) { if ( this._listeners === undefined ) { return; } var listeners = this._listeners; var listenerArray = listeners[ event.type ]; if ( listenerArray !== undefined ) { event.target = this; var array = listenerArray.slice( 0 ); for ( var i = 0, l = array.length; i < l; i ++ ) { array[ i ].call( this, event ); } } } } ); /** * @author alteredq / http://alteredqualia.com/ * @author mrdoob / http://mrdoob.com/ * @author WestLangley / http://github.com/WestLangley * @author thezwap */ var _lut = []; for ( var i = 0; i < 256; i ++ ) { _lut[ i ] = ( i < 16 ? '0' : '' ) + ( i ).toString( 16 ); } var MathUtils = { DEG2RAD: Math.PI / 180, RAD2DEG: 180 / Math.PI, generateUUID: function () { // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136 var d0 = Math.random() * 0xffffffff | 0; var d1 = Math.random() * 0xffffffff | 0; var d2 = Math.random() * 0xffffffff | 0; var d3 = Math.random() * 0xffffffff | 0; var uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' + _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' + _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] + _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ]; // .toUpperCase() here flattens concatenated strings to save heap memory space. return uuid.toUpperCase(); }, clamp: function ( value, min, max ) { return Math.max( min, Math.min( max, value ) ); }, // compute euclidian modulo of m % n // https://en.wikipedia.org/wiki/Modulo_operation euclideanModulo: function ( n, m ) { return ( ( n % m ) + m ) % m; }, // Linear mapping from range to range mapLinear: function ( x, a1, a2, b1, b2 ) { return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 ); }, // https://en.wikipedia.org/wiki/Linear_interpolation lerp: function ( x, y, t ) { return ( 1 - t ) * x + t * y; }, // http://en.wikipedia.org/wiki/Smoothstep smoothstep: function ( x, min, max ) { if ( x <= min ) { return 0; } if ( x >= max ) { return 1; } x = ( x - min ) / ( max - min ); return x * x * ( 3 - 2 * x ); }, smootherstep: function ( x, min, max ) { if ( x <= min ) { return 0; } if ( x >= max ) { return 1; } x = ( x - min ) / ( max - min ); return x * x * x * ( x * ( x * 6 - 15 ) + 10 ); }, // Random integer from interval randInt: function ( low, high ) { return low + Math.floor( Math.random() * ( high - low + 1 ) ); }, // Random float from interval randFloat: function ( low, high ) { return low + Math.random() * ( high - low ); }, // Random float from <-range/2, range/2> interval randFloatSpread: function ( range ) { return range * ( 0.5 - Math.random() ); }, degToRad: function ( degrees ) { return degrees * MathUtils.DEG2RAD; }, radToDeg: function ( radians ) { return radians * MathUtils.RAD2DEG; }, isPowerOfTwo: function ( value ) { return ( value & ( value - 1 ) ) === 0 && value !== 0; }, ceilPowerOfTwo: function ( value ) { return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) ); }, floorPowerOfTwo: function ( value ) { return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) ); }, setQuaternionFromProperEuler: function ( q, a, b, c, order ) { // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles // rotations are applied to the axes in the order specified by 'order' // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c' // angles are in radians var cos = Math.cos; var sin = Math.sin; var c2 = cos( b / 2 ); var s2 = sin( b / 2 ); var c13 = cos( ( a + c ) / 2 ); var s13 = sin( ( a + c ) / 2 ); var c1_3 = cos( ( a - c ) / 2 ); var s1_3 = sin( ( a - c ) / 2 ); var c3_1 = cos( ( c - a ) / 2 ); var s3_1 = sin( ( c - a ) / 2 ); if ( order === 'XYX' ) { q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 ); } else if ( order === 'YZY' ) { q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 ); } else if ( order === 'ZXZ' ) { q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 ); } else if ( order === 'XZX' ) { q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 ); } else if ( order === 'YXY' ) { q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 ); } else if ( order === 'ZYZ' ) { q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 ); } else { console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order.' ); } } }; /** * @author mrdoob / http://mrdoob.com/ * @author philogb / http://blog.thejit.org/ * @author egraether / http://egraether.com/ * @author zz85 / http://www.lab4games.net/zz85/blog */ function Vector2( x, y ) { this.x = x || 0; this.y = y || 0; } Object.defineProperties( Vector2.prototype, { "width": { get: function () { return this.x; }, set: function ( value ) { this.x = value; } }, "height": { get: function () { return this.y; }, set: function ( value ) { this.y = value; } } } ); Object.assign( Vector2.prototype, { isVector2: true, set: function ( x, y ) { this.x = x; this.y = y; return this; }, setScalar: function ( scalar ) { this.x = scalar; this.y = scalar; return this; }, setX: function ( x ) { this.x = x; return this; }, setY: function ( y ) { this.y = y; return this; }, setComponent: function ( index, value ) { switch ( index ) { case 0: this.x = value; break; case 1: this.y = value; break; default: throw new Error( 'index is out of range: ' + index ); } return this; }, getComponent: function ( index ) { switch ( index ) { case 0: return this.x; case 1: return this.y; default: throw new Error( 'index is out of range: ' + index ); } }, clone: function () { return new this.constructor( this.x, this.y ); }, copy: function ( v ) { this.x = v.x; this.y = v.y; return this; }, add: function ( v, w ) { if ( w !== undefined ) { console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); return this.addVectors( v, w ); } this.x += v.x; this.y += v.y; return this; }, addScalar: function ( s ) { this.x += s; this.y += s; return this; }, addVectors: function ( a, b ) { this.x = a.x + b.x; this.y = a.y + b.y; return this; }, addScaledVector: function ( v, s ) { this.x += v.x * s; this.y += v.y * s; return this; }, sub: function ( v, w ) { if ( w !== undefined ) { console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); return this.subVectors( v, w ); } this.x -= v.x; this.y -= v.y; return this; }, subScalar: function ( s ) { this.x -= s; this.y -= s; return this; }, subVectors: function ( a, b ) { this.x = a.x - b.x; this.y = a.y - b.y; return this; }, multiply: function ( v ) { this.x *= v.x; this.y *= v.y; return this; }, multiplyScalar: function ( scalar ) { this.x *= scalar; this.y *= scalar; return this; }, divide: function ( v ) { this.x /= v.x; this.y /= v.y; return this; }, divideScalar: function ( scalar ) { return this.multiplyScalar( 1 / scalar ); }, applyMatrix3: function ( m ) { var x = this.x, y = this.y; var e = m.elements; this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ]; this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ]; return this; }, min: function ( v ) { this.x = Math.min( this.x, v.x ); this.y = Math.min( this.y, v.y ); return this; }, max: function ( v ) { this.x = Math.max( this.x, v.x ); this.y = Math.max( this.y, v.y ); return this; }, clamp: function ( min, max ) { // assumes min < max, componentwise this.x = Math.max( min.x, Math.min( max.x, this.x ) ); this.y = Math.max( min.y, Math.min( max.y, this.y ) ); return this; }, clampScalar: function ( minVal, maxVal ) { this.x = Math.max( minVal, Math.min( maxVal, this.x ) ); this.y = Math.max( minVal, Math.min( maxVal, this.y ) ); return this; }, clampLength: function ( min, max ) { var length = this.length(); return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) ); }, floor: function () { this.x = Math.floor( this.x ); this.y = Math.floor( this.y ); return this; }, ceil: function () { this.x = Math.ceil( this.x ); this.y = Math.ceil( this.y ); return this; }, round: function () { this.x = Math.round( this.x ); this.y = Math.round( this.y ); return this; }, roundToZero: function () { this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x ); this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y ); return this; }, negate: function () { this.x = - this.x; this.y = - this.y; return this; }, dot: function ( v ) { return this.x * v.x + this.y * v.y; }, cross: function ( v ) { return this.x * v.y - this.y * v.x; }, lengthSq: function () { return this.x * this.x + this.y * this.y; }, length: function () { return Math.sqrt( this.x * this.x + this.y * this.y ); }, manhattanLength: function () { return Math.abs( this.x ) + Math.abs( this.y ); }, normalize: function () { return this.divideScalar( this.length() || 1 ); }, angle: function () { // computes the angle in radians with respect to the positive x-axis var angle = Math.atan2( this.y, this.x ); if ( angle < 0 ) { angle += 2 * Math.PI; } return angle; }, distanceTo: function ( v ) { return Math.sqrt( this.distanceToSquared( v ) ); }, distanceToSquared: function ( v ) { var dx = this.x - v.x, dy = this.y - v.y; return dx * dx + dy * dy; }, manhattanDistanceTo: function ( v ) { return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ); }, setLength: function ( length ) { return this.normalize().multiplyScalar( length ); }, lerp: function ( v, alpha ) { this.x += ( v.x - this.x ) * alpha; this.y += ( v.y - this.y ) * alpha; return this; }, lerpVectors: function ( v1, v2, alpha ) { return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 ); }, equals: function ( v ) { return ( ( v.x === this.x ) && ( v.y === this.y ) ); }, fromArray: function ( array, offset ) { if ( offset === undefined ) { offset = 0; } this.x = array[ offset ]; this.y = array[ offset + 1 ]; return this; }, toArray: function ( array, offset ) { if ( array === undefined ) { array = []; } if ( offset === undefined ) { offset = 0; } array[ offset ] = this.x; array[ offset + 1 ] = this.y; return array; }, fromBufferAttribute: function ( attribute, index, offset ) { if ( offset !== undefined ) { console.warn( 'THREE.Vector2: offset has been removed from .fromBufferAttribute().' ); } this.x = attribute.getX( index ); this.y = attribute.getY( index ); return this; }, rotateAround: function ( center, angle ) { var c = Math.cos( angle ), s = Math.sin( angle ); var x = this.x - center.x; var y = this.y - center.y; this.x = x * c - y * s + center.x; this.y = x * s + y * c + center.y; return this; } } ); /** * @author alteredq / http://alteredqualia.com/ * @author WestLangley / http://github.com/WestLangley * @author bhouston / http://clara.io * @author tschw */ function Matrix3() { this.elements = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ]; if ( arguments.length > 0 ) { console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' ); } } Object.assign( Matrix3.prototype, { isMatrix3: true, set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) { var te = this.elements; te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31; te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32; te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33; return this; }, identity: function () { this.set( 1, 0, 0, 0, 1, 0, 0, 0, 1 ); return this; }, clone: function () { return new this.constructor().fromArray( this.elements ); }, copy: function ( m ) { var te = this.elements; var me = m.elements; te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ]; return this; }, setFromMatrix4: function ( m ) { var me = m.elements; this.set( me[ 0 ], me[ 4 ], me[ 8 ], me[ 1 ], me[ 5 ], me[ 9 ], me[ 2 ], me[ 6 ], me[ 10 ] ); return this; }, multiply: function ( m ) { return this.multiplyMatrices( this, m ); }, premultiply: function ( m ) { return this.multiplyMatrices( m, this ); }, multiplyMatrices: function ( a, b ) { var ae = a.elements; var be = b.elements; var te = this.elements; var a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ]; var a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ]; var a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ]; var b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ]; var b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ]; var b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ]; te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31; te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32; te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33; te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31; te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32; te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33; te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31; te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32; te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33; return this; }, multiplyScalar: function ( s ) { var te = this.elements; te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s; te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s; te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s; return this; }, determinant: function () { var te = this.elements; var a = te[ 0 ], b = te[ 1 ], c = te[ 2 ], d = te[ 3 ], e = te[ 4 ], f = te[ 5 ], g = te[ 6 ], h = te[ 7 ], i = te[ 8 ]; return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g; }, getInverse: function ( matrix, throwOnDegenerate ) { if ( matrix && matrix.isMatrix4 ) { console.error( "THREE.Matrix3: .getInverse() no longer takes a Matrix4 argument." ); } var me = matrix.elements, te = this.elements, n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ], n12 = me[ 3 ], n22 = me[ 4 ], n32 = me[ 5 ], n13 = me[ 6 ], n23 = me[ 7 ], n33 = me[ 8 ], t11 = n33 * n22 - n32 * n23, t12 = n32 * n13 - n33 * n12, t13 = n23 * n12 - n22 * n13, det = n11 * t11 + n21 * t12 + n31 * t13; if ( det === 0 ) { var msg = "THREE.Matrix3: .getInverse() can't invert matrix, determinant is 0"; if ( throwOnDegenerate === true ) { throw new Error( msg ); } else { console.warn( msg ); } return this.identity(); } var detInv = 1 / det; te[ 0 ] = t11 * detInv; te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv; te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv; te[ 3 ] = t12 * detInv; te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv; te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv; te[ 6 ] = t13 * detInv; te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv; te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv; return this; }, transpose: function () { var tmp, m = this.elements; tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp; tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp; tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp; return this; }, getNormalMatrix: function ( matrix4 ) { return this.setFromMatrix4( matrix4 ).getInverse( this ).transpose(); }, transposeIntoArray: function ( r ) { var m = this.elements; r[ 0 ] = m[ 0 ]; r[ 1 ] = m[ 3 ]; r[ 2 ] = m[ 6 ]; r[ 3 ] = m[ 1 ]; r[ 4 ] = m[ 4 ]; r[ 5 ] = m[ 7 ]; r[ 6 ] = m[ 2 ]; r[ 7 ] = m[ 5 ]; r[ 8 ] = m[ 8 ]; return this; }, setUvTransform: function ( tx, ty, sx, sy, rotation, cx, cy ) { var c = Math.cos( rotation ); var s = Math.sin( rotation ); this.set( sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx, - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty, 0, 0, 1 ); }, scale: function ( sx, sy ) { var te = this.elements; te[ 0 ] *= sx; te[ 3 ] *= sx; te[ 6 ] *= sx; te[ 1 ] *= sy; te[ 4 ] *= sy; te[ 7 ] *= sy; return this; }, rotate: function ( theta ) { var c = Math.cos( theta ); var s = Math.sin( theta ); var te = this.elements; var a11 = te[ 0 ], a12 = te[ 3 ], a13 = te[ 6 ]; var a21 = te[ 1 ], a22 = te[ 4 ], a23 = te[ 7 ]; te[ 0 ] = c * a11 + s * a21; te[ 3 ] = c * a12 + s * a22; te[ 6 ] = c * a13 + s * a23; te[ 1 ] = - s * a11 + c * a21; te[ 4 ] = - s * a12 + c * a22; te[ 7 ] = - s * a13 + c * a23; return this; }, translate: function ( tx, ty ) { var te = this.elements; te[ 0 ] += tx * te[ 2 ]; te[ 3 ] += tx * te[ 5 ]; te[ 6 ] += tx * te[ 8 ]; te[ 1 ] += ty * te[ 2 ]; te[ 4 ] += ty * te[ 5 ]; te[ 7 ] += ty * te[ 8 ]; return this; }, equals: function ( matrix ) { var te = this.elements; var me = matrix.elements; for ( var i = 0; i < 9; i ++ ) { if ( te[ i ] !== me[ i ] ) { return false; } } return true; }, fromArray: function ( array, offset ) { if ( offset === undefined ) { offset = 0; } for ( var i = 0; i < 9; i ++ ) { this.elements[ i ] = array[ i + offset ]; } return this; }, toArray: function ( array, offset ) { if ( array === undefined ) { array = []; } if ( offset === undefined ) { offset = 0; } var te = this.elements; array[ offset ] = te[ 0 ]; array[ offset + 1 ] = te[ 1 ]; array[ offset + 2 ] = te[ 2 ]; array[ offset + 3 ] = te[ 3 ]; array[ offset + 4 ] = te[ 4 ]; array[ offset + 5 ] = te[ 5 ]; array[ offset + 6 ] = te[ 6 ]; array[ offset + 7 ] = te[ 7 ]; array[ offset + 8 ] = te[ 8 ]; return array; } } ); /** * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ * @author szimek / https://github.com/szimek/ */ var _canvas; var ImageUtils = { getDataURL: function ( image ) { var canvas; if ( typeof HTMLCanvasElement == 'undefined' ) { return image.src; } else if ( image instanceof HTMLCanvasElement ) { canvas = image; } else { if ( _canvas === undefined ) { _canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ); } _canvas.width = image.width; _canvas.height = image.height; var context = _canvas.getContext( '2d' ); if ( image instanceof ImageData ) { context.putImageData( image, 0, 0 ); } else { context.drawImage( image, 0, 0, image.width, image.height ); } canvas = _canvas; } if ( canvas.width > 2048 || canvas.height > 2048 ) { return canvas.toDataURL( 'image/jpeg', 0.6 ); } else { return canvas.toDataURL( 'image/png' ); } } }; /** * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ * @author szimek / https://github.com/szimek/ */ var textureId = 0; function Texture( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) { Object.defineProperty( this, 'id', { value: textureId ++ } ); this.uuid = MathUtils.generateUUID(); this.name = ''; this.image = image !== undefined ? image : Texture.DEFAULT_IMAGE; this.mipmaps = []; this.mapping = mapping !== undefined ? mapping : Texture.DEFAULT_MAPPING; this.wrapS = wrapS !== undefined ? wrapS : ClampToEdgeWrapping; this.wrapT = wrapT !== undefined ? wrapT : ClampToEdgeWrapping; this.magFilter = magFilter !== undefined ? magFilter : LinearFilter; this.minFilter = minFilter !== undefined ? minFilter : LinearMipmapLinearFilter; this.anisotropy = anisotropy !== undefined ? anisotropy : 1; this.format = format !== undefined ? format : RGBAFormat; this.internalFormat = null; this.type = type !== undefined ? type : UnsignedByteType; this.offset = new Vector2( 0, 0 ); this.repeat = new Vector2( 1, 1 ); this.center = new Vector2( 0, 0 ); this.rotation = 0; this.matrixAutoUpdate = true; this.matrix = new Matrix3(); this.generateMipmaps = true; this.premultiplyAlpha = false; this.flipY = true; this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml) // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap. // // Also changing the encoding after already used by a Material will not automatically make the Material // update. You need to explicitly call Material.needsUpdate to trigger it to recompile. this.encoding = encoding !== undefined ? encoding : LinearEncoding; this.version = 0; this.onUpdate = null; } Texture.DEFAULT_IMAGE = undefined; Texture.DEFAULT_MAPPING = UVMapping; Texture.prototype = Object.assign( Object.create( EventDispatcher.prototype ), { constructor: Texture, isTexture: true, updateMatrix: function () { this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y ); }, clone: function () { return new this.constructor().copy( this ); }, copy: function ( source ) { this.name = source.name; this.image = source.image; this.mipmaps = source.mipmaps.slice( 0 ); this.mapping = source.mapping; this.wrapS = source.wrapS; this.wrapT = source.wrapT; this.magFilter = source.magFilter; this.minFilter = source.minFilter; this.anisotropy = source.anisotropy; this.format = source.format; this.internalFormat = source.internalFormat; this.type = source.type; this.offset.copy( source.offset ); this.repeat.copy( source.repeat ); this.center.copy( source.center ); this.rotation = source.rotation; this.matrixAutoUpdate = source.matrixAutoUpdate; this.matrix.copy( source.matrix ); this.generateMipmaps = source.generateMipmaps; this.premultiplyAlpha = source.premultiplyAlpha; this.flipY = source.flipY; this.unpackAlignment = source.unpackAlignment; this.encoding = source.encoding; return this; }, toJSON: function ( meta ) { var isRootObject = ( meta === undefined || typeof meta === 'string' ); if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) { return meta.textures[ this.uuid ]; } var output = { metadata: { version: 4.5, type: 'Texture', generator: 'Texture.toJSON' }, uuid: this.uuid, name: this.name, mapping: this.mapping, repeat: [ this.repeat.x, this.repeat.y ], offset: [ this.offset.x, this.offset.y ], center: [ this.center.x, this.center.y ], rotation: this.rotation, wrap: [ this.wrapS, this.wrapT ], format: this.format, type: this.type, encoding: this.encoding, minFilter: this.minFilter, magFilter: this.magFilter, anisotropy: this.anisotropy, flipY: this.flipY, premultiplyAlpha: this.premultiplyAlpha, unpackAlignment: this.unpackAlignment }; if ( this.image !== undefined ) { // TODO: Move to THREE.Image var image = this.image; if ( image.uuid === undefined ) { image.uuid = MathUtils.generateUUID(); // UGH } if ( ! isRootObject && meta.images[ image.uuid ] === undefined ) { var url; if ( Array.isArray( image ) ) { // process array of images e.g. CubeTexture url = []; for ( var i = 0, l = image.length; i < l; i ++ ) { url.push( ImageUtils.getDataURL( image[ i ] ) ); } } else { // process single image url = ImageUtils.getDataURL( image ); } meta.images[ image.uuid ] = { uuid: image.uuid, url: url }; } output.image = image.uuid; } if ( ! isRootObject ) { meta.textures[ this.uuid ] = output; } return output; }, dispose: function () { this.dispatchEvent( { type: 'dispose' } ); }, transformUv: function ( uv ) { if ( this.mapping !== UVMapping ) { return uv; } uv.applyMatrix3( this.matrix ); if ( uv.x < 0 || uv.x > 1 ) { switch ( this.wrapS ) { case RepeatWrapping: uv.x = uv.x - Math.floor( uv.x ); break; case ClampToEdgeWrapping: uv.x = uv.x < 0 ? 0 : 1; break; case MirroredRepeatWrapping: if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) { uv.x = Math.ceil( uv.x ) - uv.x; } else { uv.x = uv.x - Math.floor( uv.x ); } break; } } if ( uv.y < 0 || uv.y > 1 ) { switch ( this.wrapT ) { case RepeatWrapping: uv.y = uv.y - Math.floor( uv.y ); break; case ClampToEdgeWrapping: uv.y = uv.y < 0 ? 0 : 1; break; case MirroredRepeatWrapping: if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) { uv.y = Math.ceil( uv.y ) - uv.y; } else { uv.y = uv.y - Math.floor( uv.y ); } break; } } if ( this.flipY ) { uv.y = 1 - uv.y; } return uv; } } ); Object.defineProperty( Texture.prototype, "needsUpdate", { set: function ( value ) { if ( value === true ) { this.version ++; } } } ); /** * @author supereggbert / http://www.paulbrunt.co.uk/ * @author philogb / http://blog.thejit.org/ * @author mikael emtinger / http://gomo.se/ * @author egraether / http://egraether.com/ * @author WestLangley / http://github.com/WestLangley */ function Vector4( x, y, z, w ) { this.x = x || 0; this.y = y || 0; this.z = z || 0; this.w = ( w !== undefined ) ? w : 1; } Object.defineProperties( Vector4.prototype, { "width": { get: function () { return this.z; }, set: function ( value ) { this.z = value; } }, "height": { get: function () { return this.w; }, set: function ( value ) { this.w = value; } } } ); Object.assign( Vector4.prototype, { isVector4: true, set: function ( x, y, z, w ) { this.x = x; this.y = y; this.z = z; this.w = w; return this; }, setScalar: function ( scalar ) { this.x = scalar; this.y = scalar; this.z = scalar; this.w = scalar; return this; }, setX: function ( x ) { this.x = x; return this; }, setY: function ( y ) { this.y = y; return this; }, setZ: function ( z ) { this.z = z; return this; }, setW: function ( w ) { this.w = w; return this; }, setComponent: function ( index, value ) { switch ( index ) { case 0: this.x = value; break; case 1: this.y = value; break; case 2: this.z = value; break; case 3: this.w = value; break; default: throw new Error( 'index is out of range: ' + index ); } return this; }, getComponent: function ( index ) { switch ( index ) { case 0: return this.x; case 1: return this.y; case 2: return this.z; case 3: return this.w; default: throw new Error( 'index is out of range: ' + index ); } }, clone: function () { return new this.constructor( this.x, this.y, this.z, this.w ); }, copy: function ( v ) { this.x = v.x; this.y = v.y; this.z = v.z; this.w = ( v.w !== undefined ) ? v.w : 1; return this; }, add: function ( v, w ) { if ( w !== undefined ) { console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); return this.addVectors( v, w ); } this.x += v.x; this.y += v.y; this.z += v.z; this.w += v.w; return this; }, addScalar: function ( s ) { this.x += s; this.y += s; this.z += s; this.w += s; return this; }, addVectors: function ( a, b ) { this.x = a.x + b.x; this.y = a.y + b.y; this.z = a.z + b.z; this.w = a.w + b.w; return this; }, addScaledVector: function ( v, s ) { this.x += v.x * s; this.y += v.y * s; this.z += v.z * s; this.w += v.w * s; return this; }, sub: function ( v, w ) { if ( w !== undefined ) { console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); return this.subVectors( v, w ); } this.x -= v.x; this.y -= v.y; this.z -= v.z; this.w -= v.w; return this; }, subScalar: function ( s ) { this.x -= s; this.y -= s; this.z -= s; this.w -= s; return this; }, subVectors: function ( a, b ) { this.x = a.x - b.x; this.y = a.y - b.y; this.z = a.z - b.z; this.w = a.w - b.w; return this; }, multiplyScalar: function ( scalar ) { this.x *= scalar; this.y *= scalar; this.z *= scalar; this.w *= scalar; return this; }, applyMatrix4: function ( m ) { var x = this.x, y = this.y, z = this.z, w = this.w; var e = m.elements; this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w; this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w; this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w; this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w; return this; }, divideScalar: function ( scalar ) { return this.multiplyScalar( 1 / scalar ); }, setAxisAngleFromQuaternion: function ( q ) { // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm // q is assumed to be normalized this.w = 2 * Math.acos( q.w ); var s = Math.sqrt( 1 - q.w * q.w ); if ( s < 0.0001 ) { this.x = 1; this.y = 0; this.z = 0; } else { this.x = q.x / s; this.y = q.y / s; this.z = q.z / s; } return this; }, setAxisAngleFromRotationMatrix: function ( m ) { // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) var angle, x, y, z, // variables for result epsilon = 0.01, // margin to allow for rounding errors epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees te = m.elements, m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ], m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ], m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ]; if ( ( Math.abs( m12 - m21 ) < epsilon ) && ( Math.abs( m13 - m31 ) < epsilon ) && ( Math.abs( m23 - m32 ) < epsilon ) ) { // singularity found // first check for identity matrix which must have +1 for all terms // in leading diagonal and zero in other terms if ( ( Math.abs( m12 + m21 ) < epsilon2 ) && ( Math.abs( m13 + m31 ) < epsilon2 ) && ( Math.abs( m23 + m32 ) < epsilon2 ) && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) { // this singularity is identity matrix so angle = 0 this.set( 1, 0, 0, 0 ); return this; // zero angle, arbitrary axis } // otherwise this singularity is angle = 180 angle = Math.PI; var xx = ( m11 + 1 ) / 2; var yy = ( m22 + 1 ) / 2; var zz = ( m33 + 1 ) / 2; var xy = ( m12 + m21 ) / 4; var xz = ( m13 + m31 ) / 4; var yz = ( m23 + m32 ) / 4; if ( ( xx > yy ) && ( xx > zz ) ) { // m11 is the largest diagonal term if ( xx < epsilon ) { x = 0; y = 0.707106781; z = 0.707106781; } else { x = Math.sqrt( xx ); y = xy / x; z = xz / x; } } else if ( yy > zz ) { // m22 is the largest diagonal term if ( yy < epsilon ) { x = 0.707106781; y = 0; z = 0.707106781; } else { y = Math.sqrt( yy ); x = xy / y; z = yz / y; } } else { // m33 is the largest diagonal term so base result on this if ( zz < epsilon ) { x = 0.707106781; y = 0.707106781; z = 0; } else { z = Math.sqrt( zz ); x = xz / z; y = yz / z; } } this.set( x, y, z, angle ); return this; // return 180 deg rotation } // as we have reached here there are no singularities so we can handle normally var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) + ( m13 - m31 ) * ( m13 - m31 ) + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize if ( Math.abs( s ) < 0.001 ) { s = 1; } // prevent divide by zero, should not happen if matrix is orthogonal and should be // caught by singularity test above, but I've left it in just in case this.x = ( m32 - m23 ) / s; this.y = ( m13 - m31 ) / s; this.z = ( m21 - m12 ) / s; this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 ); return this; }, min: function ( v ) { this.x = Math.min( this.x, v.x ); this.y = Math.min( this.y, v.y ); this.z = Math.min( this.z, v.z ); this.w = Math.min( this.w, v.w ); return this; }, max: function ( v ) { this.x = Math.max( this.x, v.x ); this.y = Math.max( this.y, v.y ); this.z = Math.max( this.z, v.z ); this.w = Math.max( this.w, v.w ); return this; }, clamp: function ( min, max ) { // assumes min < max, componentwise this.x = Math.max( min.x, Math.min( max.x, this.x ) ); this.y = Math.max( min.y, Math.min( max.y, this.y ) ); this.z = Math.max( min.z, Math.min( max.z, this.z ) ); this.w = Math.max( min.w, Math.min( max.w, this.w ) ); return this; }, clampScalar: function ( minVal, maxVal ) { this.x = Math.max( minVal, Math.min( maxVal, this.x ) ); this.y = Math.max( minVal, Math.min( maxVal, this.y ) ); this.z = Math.max( minVal, Math.min( maxVal, this.z ) ); this.w = Math.max( minVal, Math.min( maxVal, this.w ) ); return this; }, clampLength: function ( min, max ) { var length = this.length(); return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) ); }, floor: function () { this.x = Math.floor( this.x ); this.y = Math.floor( this.y ); this.z = Math.floor( this.z ); this.w = Math.floor( this.w ); return this; }, ceil: function () { this.x = Math.ceil( this.x ); this.y = Math.ceil( this.y ); this.z = Math.ceil( this.z ); this.w = Math.ceil( this.w ); return this; }, round: function () { this.x = Math.round( this.x ); this.y = Math.round( this.y ); this.z = Math.round( this.z ); this.w = Math.round( this.w ); return this; }, roundToZero: function () { this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x ); this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y ); this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z ); this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w ); return this; }, negate: function () { this.x = - this.x; this.y = - this.y; this.z = - this.z; this.w = - this.w; return this; }, dot: function ( v ) { return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w; }, lengthSq: function () { return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w; }, length: function () { return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w ); }, manhattanLength: function () { return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w ); }, normalize: function () { return this.divideScalar( this.length() || 1 ); }, setLength: function ( length ) { return this.normalize().multiplyScalar( length ); }, lerp: function ( v, alpha ) { this.x += ( v.x - this.x ) * alpha; this.y += ( v.y - this.y ) * alpha; this.z += ( v.z - this.z ) * alpha; this.w += ( v.w - this.w ) * alpha; return this; }, lerpVectors: function ( v1, v2, alpha ) { return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 ); }, equals: function ( v ) { return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) ); }, fromArray: function ( array, offset ) { if ( offset === undefined ) { offset = 0; } this.x = array[ offset ]; this.y = array[ offset + 1 ]; this.z = array[ offset + 2 ]; this.w = array[ offset + 3 ]; return this; }, toArray: function ( array, offset ) { if ( array === undefined ) { array = []; } if ( offset === undefined ) { offset = 0; } array[ offset ] = this.x; array[ offset + 1 ] = this.y; array[ offset + 2 ] = this.z; array[ offset + 3 ] = this.w; return array; }, fromBufferAttribute: function ( attribute, index, offset ) { if ( offset !== undefined ) { console.warn( 'THREE.Vector4: offset has been removed from .fromBufferAttribute().' ); } this.x = attribute.getX( index ); this.y = attribute.getY( index ); this.z = attribute.getZ( index ); this.w = attribute.getW( index ); return this; } } ); /** * @author szimek / https://github.com/szimek/ * @author alteredq / http://alteredqualia.com/ * @author Marius Kintel / https://github.com/kintel */ /* In options, we can specify: * Texture parameters for an auto-generated target texture * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers */ function WebGLRenderTarget( width, height, options ) { this.width = width; this.height = height; this.scissor = new Vector4( 0, 0, width, height ); this.scissorTest = false; this.viewport = new Vector4( 0, 0, width, height ); options = options || {}; this.texture = new Texture( undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding ); this.texture.image = {}; this.texture.image.width = width; this.texture.image.height = height; this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false; this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter; this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true; this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true; this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null; } WebGLRenderTarget.prototype = Object.assign( Object.create( EventDispatcher.prototype ), { constructor: WebGLRenderTarget, isWebGLRenderTarget: true, setSize: function ( width, height ) { if ( this.width !== width || this.height !== height ) { this.width = width; this.height = height; this.texture.image.width = width; this.texture.image.height = height; this.dispose(); } this.viewport.set( 0, 0, width, height ); this.scissor.set( 0, 0, width, height ); }, clone: function () { return new this.constructor().copy( this ); }, copy: function ( source ) { this.width = source.width; this.height = source.height; this.viewport.copy( source.viewport ); this.texture = source.texture.clone(); this.depthBuffer = source.depthBuffer; this.stencilBuffer = source.stencilBuffer; this.depthTexture = source.depthTexture; return this; }, dispose: function () { this.dispatchEvent( { type: 'dispose' } ); } } ); /** * @author Mugen87 / https://github.com/Mugen87 * @author Matt DesLauriers / @mattdesl */ function WebGLMultisampleRenderTarget( width, height, options ) { WebGLRenderTarget.call( this, width, height, options ); this.samples = 4; } WebGLMultisampleRenderTarget.prototype = Object.assign( Object.create( WebGLRenderTarget.prototype ), { constructor: WebGLMultisampleRenderTarget, isWebGLMultisampleRenderTarget: true, copy: function ( source ) { WebGLRenderTarget.prototype.copy.call( this, source ); this.samples = source.samples; return this; } } ); /** * @author mikael emtinger / http://gomo.se/ * @author alteredq / http://alteredqualia.com/ * @author WestLangley / http://github.com/WestLangley * @author bhouston / http://clara.io */ function Quaternion( x, y, z, w ) { this._x = x || 0; this._y = y || 0; this._z = z || 0; this._w = ( w !== undefined ) ? w : 1; } Object.assign( Quaternion, { slerp: function ( qa, qb, qm, t ) { return qm.copy( qa ).slerp( qb, t ); }, slerpFlat: function ( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) { // fuzz-free, array-based Quaternion SLERP operation var x0 = src0[ srcOffset0 + 0 ], y0 = src0[ srcOffset0 + 1 ], z0 = src0[ srcOffset0 + 2 ], w0 = src0[ srcOffset0 + 3 ], x1 = src1[ srcOffset1 + 0 ], y1 = src1[ srcOffset1 + 1 ], z1 = src1[ srcOffset1 + 2 ], w1 = src1[ srcOffset1 + 3 ]; if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) { var s = 1 - t, cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1, dir = ( cos >= 0 ? 1 : - 1 ), sqrSin = 1 - cos * cos; // Skip the Slerp for tiny steps to avoid numeric problems: if ( sqrSin > Number.EPSILON ) { var sin = Math.sqrt( sqrSin ), len = Math.atan2( sin, cos * dir ); s = Math.sin( s * len ) / sin; t = Math.sin( t * len ) / sin; } var tDir = t * dir; x0 = x0 * s + x1 * tDir; y0 = y0 * s + y1 * tDir; z0 = z0 * s + z1 * tDir; w0 = w0 * s + w1 * tDir; // Normalize in case we just did a lerp: if ( s === 1 - t ) { var f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 ); x0 *= f; y0 *= f; z0 *= f; w0 *= f; } } dst[ dstOffset ] = x0; dst[ dstOffset + 1 ] = y0; dst[ dstOffset + 2 ] = z0; dst[ dstOffset + 3 ] = w0; } } ); Object.defineProperties( Quaternion.prototype, { x: { get: function () { return this._x; }, set: function ( value ) { this._x = value; this._onChangeCallback(); } }, y: { get: function () { return this._y; }, set: function ( value ) { this._y = value; this._onChangeCallback(); } }, z: { get: function () { return this._z; }, set: function ( value ) { this._z = value; this._onChangeCallback(); } }, w: { get: function () { return this._w; }, set: function ( value ) { this._w = value; this._onChangeCallback(); } } } ); Object.assign( Quaternion.prototype, { isQuaternion: true, set: function ( x, y, z, w ) { this._x = x; this._y = y; this._z = z; this._w = w; this._onChangeCallback(); return this; }, clone: function () { return new this.constructor( this._x, this._y, this._z, this._w ); }, copy: function ( quaternion ) { this._x = quaternion.x; this._y = quaternion.y; this._z = quaternion.z; this._w = quaternion.w; this._onChangeCallback(); return this; }, setFromEuler: function ( euler, update ) { if ( ! ( euler && euler.isEuler ) ) { throw new Error( 'THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.' ); } var x = euler._x, y = euler._y, z = euler._z, order = euler.order; // http://www.mathworks.com/matlabcentral/fileexchange/ // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/ // content/SpinCalc.m var cos = Math.cos; var sin = Math.sin; var c1 = cos( x / 2 ); var c2 = cos( y / 2 ); var c3 = cos( z / 2 ); var s1 = sin( x / 2 ); var s2 = sin( y / 2 ); var s3 = sin( z / 2 ); if ( order === 'XYZ' ) { this._x = s1 * c2 * c3 + c1 * s2 * s3; this._y = c1 * s2 * c3 - s1 * c2 * s3; this._z = c1 * c2 * s3 + s1 * s2 * c3; this._w = c1 * c2 * c3 - s1 * s2 * s3; } else if ( order === 'YXZ' ) { this._x = s1 * c2 * c3 + c1 * s2 * s3; this._y = c1 * s2 * c3 - s1 * c2 * s3; this._z = c1 * c2 * s3 - s1 * s2 * c3; this._w = c1 * c2 * c3 + s1 * s2 * s3; } else if ( order === 'ZXY' ) { this._x = s1 * c2 * c3 - c1 * s2 * s3; this._y = c1 * s2 * c3 + s1 * c2 * s3; this._z = c1 * c2 * s3 + s1 * s2 * c3; this._w = c1 * c2 * c3 - s1 * s2 * s3; } else if ( order === 'ZYX' ) { this._x = s1 * c2 * c3 - c1 * s2 * s3; this._y = c1 * s2 * c3 + s1 * c2 * s3; this._z = c1 * c2 * s3 - s1 * s2 * c3; this._w = c1 * c2 * c3 + s1 * s2 * s3; } else if ( order === 'YZX' ) { this._x = s1 * c2 * c3 + c1 * s2 * s3; this._y = c1 * s2 * c3 + s1 * c2 * s3; this._z = c1 * c2 * s3 - s1 * s2 * c3; this._w = c1 * c2 * c3 - s1 * s2 * s3; } else if ( order === 'XZY' ) { this._x = s1 * c2 * c3 - c1 * s2 * s3; this._y = c1 * s2 * c3 - s1 * c2 * s3; this._z = c1 * c2 * s3 + s1 * s2 * c3; this._w = c1 * c2 * c3 + s1 * s2 * s3; } if ( update !== false ) { this._onChangeCallback(); } return this; }, setFromAxisAngle: function ( axis, angle ) { // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm // assumes axis is normalized var halfAngle = angle / 2, s = Math.sin( halfAngle ); this._x = axis.x * s; this._y = axis.y * s; this._z = axis.z * s; this._w = Math.cos( halfAngle ); this._onChangeCallback(); return this; }, setFromRotationMatrix: function ( m ) { // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) var te = m.elements, m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ], m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ], m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ], trace = m11 + m22 + m33, s; if ( trace > 0 ) { s = 0.5 / Math.sqrt( trace + 1.0 ); this._w = 0.25 / s; this._x = ( m32 - m23 ) * s; this._y = ( m13 - m31 ) * s; this._z = ( m21 - m12 ) * s; } else if ( m11 > m22 && m11 > m33 ) { s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 ); this._w = ( m32 - m23 ) / s; this._x = 0.25 * s; this._y = ( m12 + m21 ) / s; this._z = ( m13 + m31 ) / s; } else if ( m22 > m33 ) { s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 ); this._w = ( m13 - m31 ) / s; this._x = ( m12 + m21 ) / s; this._y = 0.25 * s; this._z = ( m23 + m32 ) / s; } else { s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 ); this._w = ( m21 - m12 ) / s; this._x = ( m13 + m31 ) / s; this._y = ( m23 + m32 ) / s; this._z = 0.25 * s; } this._onChangeCallback(); return this; }, setFromUnitVectors: function ( vFrom, vTo ) { // assumes direction vectors vFrom and vTo are normalized var EPS = 0.000001; var r = vFrom.dot( vTo ) + 1; if ( r < EPS ) { r = 0; if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) { this._x = - vFrom.y; this._y = vFrom.x; this._z = 0; this._w = r; } else { this._x = 0; this._y = - vFrom.z; this._z = vFrom.y; this._w = r; } } else { // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3 this._x = vFrom.y * vTo.z - vFrom.z * vTo.y; this._y = vFrom.z * vTo.x - vFrom.x * vTo.z; this._z = vFrom.x * vTo.y - vFrom.y * vTo.x; this._w = r; } return this.normalize(); }, angleTo: function ( q ) { return 2 * Math.acos( Math.abs( MathUtils.clamp( this.dot( q ), - 1, 1 ) ) ); }, rotateTowards: function ( q, step ) { var angle = this.angleTo( q ); if ( angle === 0 ) { return this; } var t = Math.min( 1, step / angle ); this.slerp( q, t ); return this; }, inverse: function () { // quaternion is assumed to have unit length return this.conjugate(); }, conjugate: function () { this._x *= - 1; this._y *= - 1; this._z *= - 1; this._onChangeCallback(); return this; }, dot: function ( v ) { return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w; }, lengthSq: function () { return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w; }, length: function () { return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w ); }, normalize: function () { var l = this.length(); if ( l === 0 ) { this._x = 0; this._y = 0; this._z = 0; this._w = 1; } else { l = 1 / l; this._x = this._x * l; this._y = this._y * l; this._z = this._z * l; this._w = this._w * l; } this._onChangeCallback(); return this; }, multiply: function ( q, p ) { if ( p !== undefined ) { console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' ); return this.multiplyQuaternions( q, p ); } return this.multiplyQuaternions( this, q ); }, premultiply: function ( q ) { return this.multiplyQuaternions( q, this ); }, multiplyQuaternions: function ( a, b ) { // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w; var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w; this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby; this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz; this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx; this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz; this._onChangeCallback(); return this; }, slerp: function ( qb, t ) { if ( t === 0 ) { return this; } if ( t === 1 ) { return this.copy( qb ); } var x = this._x, y = this._y, z = this._z, w = this._w; // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/ var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z; if ( cosHalfTheta < 0 ) { this._w = - qb._w; this._x = - qb._x; this._y = - qb._y; this._z = - qb._z; cosHalfTheta = - cosHalfTheta; } else { this.copy( qb ); } if ( cosHalfTheta >= 1.0 ) { this._w = w; this._x = x; this._y = y; this._z = z; return this; } var sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta; if ( sqrSinHalfTheta <= Number.EPSILON ) { var s = 1 - t; this._w = s * w + t * this._w; this._x = s * x + t * this._x; this._y = s * y + t * this._y; this._z = s * z + t * this._z; this.normalize(); this._onChangeCallback(); return this; } var sinHalfTheta = Math.sqrt( sqrSinHalfTheta ); var halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta ); var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta, ratioB = Math.sin( t * halfTheta ) / sinHalfTheta; this._w = ( w * ratioA + this._w * ratioB ); this._x = ( x * ratioA + this._x * ratioB ); this._y = ( y * ratioA + this._y * ratioB ); this._z = ( z * ratioA + this._z * ratioB ); this._onChangeCallback(); return this; }, equals: function ( quaternion ) { return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w ); }, fromArray: function ( array, offset ) { if ( offset === undefined ) { offset = 0; } this._x = array[ offset ]; this._y = array[ offset + 1 ]; this._z = array[ offset + 2 ]; this._w = array[ offset + 3 ]; this._onChangeCallback(); return this; }, toArray: function ( array, offset ) { if ( array === undefined ) { array = []; } if ( offset === undefined ) { offset = 0; } array[ offset ] = this._x; array[ offset + 1 ] = this._y; array[ offset + 2 ] = this._z; array[ offset + 3 ] = this._w; return array; }, _onChange: function ( callback ) { this._onChangeCallback = callback; return this; }, _onChangeCallback: function () {} } ); /** * @author mrdoob / http://mrdoob.com/ * @author kile / http://kile.stravaganza.org/ * @author philogb / http://blog.thejit.org/ * @author mikael emtinger / http://gomo.se/ * @author egraether / http://egraether.com/ * @author WestLangley / http://github.com/WestLangley */ var _vector = new Vector3(); var _quaternion = new Quaternion(); function Vector3( x, y, z ) { this.x = x || 0; this.y = y || 0; this.z = z || 0; } Object.assign( Vector3.prototype, { isVector3: true, set: function ( x, y, z ) { this.x = x; this.y = y; this.z = z; return this; }, setScalar: function ( scalar ) { this.x = scalar; this.y = scalar; this.z = scalar; return this; }, setX: function ( x ) { this.x = x; return this; }, setY: function ( y ) { this.y = y; return this; }, setZ: function ( z ) { this.z = z; return this; }, setComponent: function ( index, value ) { switch ( index ) { case 0: this.x = value; break; case 1: this.y = value; break; case 2: this.z = value; break; default: throw new Error( 'index is out of range: ' + index ); } return this; }, getComponent: function ( index ) { switch ( index ) { case 0: return this.x; case 1: return this.y; case 2: return this.z; default: throw new Error( 'index is out of range: ' + index ); } }, clone: function () { return new this.constructor( this.x, this.y, this.z ); }, copy: function ( v ) { this.x = v.x; this.y = v.y; this.z = v.z; return this; }, add: function ( v, w ) { if ( w !== undefined ) { console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); return this.addVectors( v, w ); } this.x += v.x; this.y += v.y; this.z += v.z; return this; }, addScalar: function ( s ) { this.x += s; this.y += s; this.z += s; return this; }, addVectors: function ( a, b ) { this.x = a.x + b.x; this.y = a.y + b.y; this.z = a.z + b.z; return this; }, addScaledVector: function ( v, s ) { this.x += v.x * s; this.y += v.y * s; this.z += v.z * s; return this; }, sub: function ( v, w ) { if ( w !== undefined ) { console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); return this.subVectors( v, w ); } this.x -= v.x; this.y -= v.y; this.z -= v.z; return this; }, subScalar: function ( s ) { this.x -= s; this.y -= s; this.z -= s; return this; }, subVectors: function ( a, b ) { this.x = a.x - b.x; this.y = a.y - b.y; this.z = a.z - b.z; return this; }, multiply: function ( v, w ) { if ( w !== undefined ) { console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' ); return this.multiplyVectors( v, w ); } this.x *= v.x; this.y *= v.y; this.z *= v.z; return this; }, multiplyScalar: function ( scalar ) { this.x *= scalar; this.y *= scalar; this.z *= scalar; return this; }, multiplyVectors: function ( a, b ) { this.x = a.x * b.x; this.y = a.y * b.y; this.z = a.z * b.z; return this; }, applyEuler: function ( euler ) { if ( ! ( euler && euler.isEuler ) ) { console.error( 'THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.' ); } return this.applyQuaternion( _quaternion.setFromEuler( euler ) ); }, applyAxisAngle: function ( axis, angle ) { return this.applyQuaternion( _quaternion.setFromAxisAngle( axis, angle ) ); }, applyMatrix3: function ( m ) { var x = this.x, y = this.y, z = this.z; var e = m.elements; this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z; this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z; this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z; return this; }, applyNormalMatrix: function ( m ) { return this.applyMatrix3( m ).normalize(); }, applyMatrix4: function ( m ) { var x = this.x, y = this.y, z = this.z; var e = m.elements; var w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] ); this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w; this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w; this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w; return this; }, applyQuaternion: function ( q ) { var x = this.x, y = this.y, z = this.z; var qx = q.x, qy = q.y, qz = q.z, qw = q.w; // calculate quat * vector var ix = qw * x + qy * z - qz * y; var iy = qw * y + qz * x - qx * z; var iz = qw * z + qx * y - qy * x; var iw = - qx * x - qy * y - qz * z; // calculate result * inverse quat this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy; this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz; this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx; return this; }, project: function ( camera ) { return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix ); }, unproject: function ( camera ) { return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld ); }, transformDirection: function ( m ) { // input: THREE.Matrix4 affine matrix // vector interpreted as a direction var x = this.x, y = this.y, z = this.z; var e = m.elements; this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z; this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z; this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z; return this.normalize(); }, divide: function ( v ) { this.x /= v.x; this.y /= v.y; this.z /= v.z; return this; }, divideScalar: function ( scalar ) { return this.multiplyScalar( 1 / scalar ); }, min: function ( v ) { this.x = Math.min( this.x, v.x ); this.y = Math.min( this.y, v.y ); this.z = Math.min( this.z, v.z ); return this; }, max: function ( v ) { this.x = Math.max( this.x, v.x ); this.y = Math.max( this.y, v.y ); this.z = Math.max( this.z, v.z ); return this; }, clamp: function ( min, max ) { // assumes min < max, componentwise this.x = Math.max( min.x, Math.min( max.x, this.x ) ); this.y = Math.max( min.y, Math.min( max.y, this.y ) ); this.z = Math.max( min.z, Math.min( max.z, this.z ) ); return this; }, clampScalar: function ( minVal, maxVal ) { this.x = Math.max( minVal, Math.min( maxVal, this.x ) ); this.y = Math.max( minVal, Math.min( maxVal, this.y ) ); this.z = Math.max( minVal, Math.min( maxVal, this.z ) ); return this; }, clampLength: function ( min, max ) { var length = this.length(); return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) ); }, floor: function () { this.x = Math.floor( this.x ); this.y = Math.floor( this.y ); this.z = Math.floor( this.z ); return this; }, ceil: function () { this.x = Math.ceil( this.x ); this.y = Math.ceil( this.y ); this.z = Math.ceil( this.z ); return this; }, round: function () { this.x = Math.round( this.x ); this.y = Math.round( this.y ); this.z = Math.round( this.z ); return this; }, roundToZero: function () { this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x ); this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y ); this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z ); return this; }, negate: function () { this.x = - this.x; this.y = - this.y; this.z = - this.z; return this; }, dot: function ( v ) { return this.x * v.x + this.y * v.y + this.z * v.z; }, // TODO lengthSquared? lengthSq: function () { return this.x * this.x + this.y * this.y + this.z * this.z; }, length: function () { return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z ); }, manhattanLength: function () { return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ); }, normalize: function () { return this.divideScalar( this.length() || 1 ); }, setLength: function ( length ) { return this.normalize().multiplyScalar( length ); }, lerp: function ( v, alpha ) { this.x += ( v.x - this.x ) * alpha; this.y += ( v.y - this.y ) * alpha; this.z += ( v.z - this.z ) * alpha; return this; }, lerpVectors: function ( v1, v2, alpha ) { return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 ); }, cross: function ( v, w ) { if ( w !== undefined ) { console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' ); return this.crossVectors( v, w ); } return this.crossVectors( this, v ); }, crossVectors: function ( a, b ) { var ax = a.x, ay = a.y, az = a.z; var bx = b.x, by = b.y, bz = b.z; this.x = ay * bz - az * by; this.y = az * bx - ax * bz; this.z = ax * by - ay * bx; return this; }, projectOnVector: function ( v ) { var denominator = v.lengthSq(); if ( denominator === 0 ) { return this.set( 0, 0, 0 ); } var scalar = v.dot( this ) / denominator; return this.copy( v ).multiplyScalar( scalar ); }, projectOnPlane: function ( planeNormal ) { _vector.copy( this ).projectOnVector( planeNormal ); return this.sub( _vector ); }, reflect: function ( normal ) { // reflect incident vector off plane orthogonal to normal // normal is assumed to have unit length return this.sub( _vector.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) ); }, angleTo: function ( v ) { var denominator = Math.sqrt( this.lengthSq() * v.lengthSq() ); if ( denominator === 0 ) { return Math.PI / 2; } var theta = this.dot( v ) / denominator; // clamp, to handle numerical problems return Math.acos( MathUtils.clamp( theta, - 1, 1 ) ); }, distanceTo: function ( v ) { return Math.sqrt( this.distanceToSquared( v ) ); }, distanceToSquared: function ( v ) { var dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z; return dx * dx + dy * dy + dz * dz; }, manhattanDistanceTo: function ( v ) { return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z ); }, setFromSpherical: function ( s ) { return this.setFromSphericalCoords( s.radius, s.phi, s.theta ); }, setFromSphericalCoords: function ( radius, phi, theta ) { var sinPhiRadius = Math.sin( phi ) * radius; this.x = sinPhiRadius * Math.sin( theta ); this.y = Math.cos( phi ) * radius; this.z = sinPhiRadius * Math.cos( theta ); return this; }, setFromCylindrical: function ( c ) { return this.setFromCylindricalCoords( c.radius, c.theta, c.y ); }, setFromCylindricalCoords: function ( radius, theta, y ) { this.x = radius * Math.sin( theta ); this.y = y; this.z = radius * Math.cos( theta ); return this; }, setFromMatrixPosition: function ( m ) { var e = m.elements; this.x = e[ 12 ]; this.y = e[ 13 ]; this.z = e[ 14 ]; return this; }, setFromMatrixScale: function ( m ) { var sx = this.setFromMatrixColumn( m, 0 ).length(); var sy = this.setFromMatrixColumn( m, 1 ).length(); var sz = this.setFromMatrixColumn( m, 2 ).length(); this.x = sx; this.y = sy; this.z = sz; return this; }, setFromMatrixColumn: function ( m, index ) { return this.fromArray( m.elements, index * 4 ); }, setFromMatrix3Column: function ( m, index ) { return this.fromArray( m.elements, index * 3 ); }, equals: function ( v ) { return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) ); }, fromArray: function ( array, offset ) { if ( offset === undefined ) { offset = 0; } this.x = array[ offset ]; this.y = array[ offset + 1 ]; this.z = array[ offset + 2 ]; return this; }, toArray: function ( array, offset ) { if ( array === undefined ) { array = []; } if ( offset === undefined ) { offset = 0; } array[ offset ] = this.x; array[ offset + 1 ] = this.y; array[ offset + 2 ] = this.z; return array; }, fromBufferAttribute: function ( attribute, index, offset ) { if ( offset !== undefined ) { console.warn( 'THREE.Vector3: offset has been removed from .fromBufferAttribute().' ); } this.x = attribute.getX( index ); this.y = attribute.getY( index ); this.z = attribute.getZ( index ); return this; } } ); var _v1 = new Vector3(); var _m1 = new Matrix4(); var _zero = new Vector3( 0, 0, 0 ); var _one = new Vector3( 1, 1, 1 ); var _x = new Vector3(); var _y = new Vector3(); var _z = new Vector3(); /** * @author mrdoob / http://mrdoob.com/ * @author supereggbert / http://www.paulbrunt.co.uk/ * @author philogb / http://blog.thejit.org/ * @author jordi_ros / http://plattsoft.com * @author D1plo1d / http://github.com/D1plo1d * @author alteredq / http://alteredqualia.com/ * @author mikael emtinger / http://gomo.se/ * @author timknip / http://www.floorplanner.com/ * @author bhouston / http://clara.io * @author WestLangley / http://github.com/WestLangley */ function Matrix4() { this.elements = [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ]; if ( arguments.length > 0 ) { console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' ); } } Object.assign( Matrix4.prototype, { isMatrix4: true, set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) { var te = this.elements; te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14; te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24; te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34; te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44; return this; }, identity: function () { this.set( 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ); return this; }, clone: function () { return new Matrix4().fromArray( this.elements ); }, copy: function ( m ) { var te = this.elements; var me = m.elements; te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ]; te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ]; return this; }, copyPosition: function ( m ) { var te = this.elements, me = m.elements; te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; return this; }, extractBasis: function ( xAxis, yAxis, zAxis ) { xAxis.setFromMatrixColumn( this, 0 ); yAxis.setFromMatrixColumn( this, 1 ); zAxis.setFromMatrixColumn( this, 2 ); return this; }, makeBasis: function ( xAxis, yAxis, zAxis ) { this.set( xAxis.x, yAxis.x, zAxis.x, 0, xAxis.y, yAxis.y, zAxis.y, 0, xAxis.z, yAxis.z, zAxis.z, 0, 0, 0, 0, 1 ); return this; }, extractRotation: function ( m ) { // this method does not support reflection matrices var te = this.elements; var me = m.elements; var scaleX = 1 / _v1.setFromMatrixColumn( m, 0 ).length(); var scaleY = 1 / _v1.setFromMatrixColumn( m, 1 ).length(); var scaleZ = 1 / _v1.setFromMatrixColumn( m, 2 ).length(); te[ 0 ] = me[ 0 ] * scaleX; te[ 1 ] = me[ 1 ] * scaleX; te[ 2 ] = me[ 2 ] * scaleX; te[ 3 ] = 0; te[ 4 ] = me[ 4 ] * scaleY; te[ 5 ] = me[ 5 ] * scaleY; te[ 6 ] = me[ 6 ] * scaleY; te[ 7 ] = 0; te[ 8 ] = me[ 8 ] * scaleZ; te[ 9 ] = me[ 9 ] * scaleZ; te[ 10 ] = me[ 10 ] * scaleZ; te[ 11 ] = 0; te[ 12 ] = 0; te[ 13 ] = 0; te[ 14 ] = 0; te[ 15 ] = 1; return this; }, makeRotationFromEuler: function ( euler ) { if ( ! ( euler && euler.isEuler ) ) { console.error( 'THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' ); } var te = this.elements; var x = euler.x, y = euler.y, z = euler.z; var a = Math.cos( x ), b = Math.sin( x ); var c = Math.cos( y ), d = Math.sin( y ); var e = Math.cos( z ), f = Math.sin( z ); if ( euler.order === 'XYZ' ) { var ae = a * e, af = a * f, be = b * e, bf = b * f; te[ 0 ] = c * e; te[ 4 ] = - c * f; te[ 8 ] = d; te[ 1 ] = af + be * d; te[ 5 ] = ae - bf * d; te[ 9 ] = - b * c; te[ 2 ] = bf - ae * d; te[ 6 ] = be + af * d; te[ 10 ] = a * c; } else if ( euler.order === 'YXZ' ) { var ce = c * e, cf = c * f, de = d * e, df = d * f; te[ 0 ] = ce + df * b; te[ 4 ] = de * b - cf; te[ 8 ] = a * d; te[ 1 ] = a * f; te[ 5 ] = a * e; te[ 9 ] = - b; te[ 2 ] = cf * b - de; te[ 6 ] = df + ce * b; te[ 10 ] = a * c; } else if ( euler.order === 'ZXY' ) { var ce = c * e, cf = c * f, de = d * e, df = d * f; te[ 0 ] = ce - df * b; te[ 4 ] = - a * f; te[ 8 ] = de + cf * b; te[ 1 ] = cf + de * b; te[ 5 ] = a * e; te[ 9 ] = df - ce * b; te[ 2 ] = - a * d; te[ 6 ] = b; te[ 10 ] = a * c; } else if ( euler.order === 'ZYX' ) { var ae = a * e, af = a * f, be = b * e, bf = b * f; te[ 0 ] = c * e; te[ 4 ] = be * d - af; te[ 8 ] = ae * d + bf; te[ 1 ] = c * f; te[ 5 ] = bf * d + ae; te[ 9 ] = af * d - be; te[ 2 ] = - d; te[ 6 ] = b * c; te[ 10 ] = a * c; } else if ( euler.order === 'YZX' ) { var ac = a * c, ad = a * d, bc = b * c, bd = b * d; te[ 0 ] = c * e; te[ 4 ] = bd - ac * f; te[ 8 ] = bc * f + ad; te[ 1 ] = f; te[ 5 ] = a * e; te[ 9 ] = - b * e; te[ 2 ] = - d * e; te[ 6 ] = ad * f + bc; te[ 10 ] = ac - bd * f; } else if ( euler.order === 'XZY' ) { var ac = a * c, ad = a * d, bc = b * c, bd = b * d; te[ 0 ] = c * e; te[ 4 ] = - f; te[ 8 ] = d * e; te[ 1 ] = ac * f + bd; te[ 5 ] = a * e; te[ 9 ] = ad * f - bc; te[ 2 ] = bc * f - ad; te[ 6 ] = b * e; te[ 10 ] = bd * f + ac; } // bottom row te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; // last column te[ 12 ] = 0; te[ 13 ] = 0; te[ 14 ] = 0; te[ 15 ] = 1; return this; }, makeRotationFromQuaternion: function ( q ) { return this.compose( _zero, q, _one ); }, lookAt: function ( eye, target, up ) { var te = this.elements; _z.subVectors( eye, target ); if ( _z.lengthSq() === 0 ) { // eye and target are in the same position _z.z = 1; } _z.normalize(); _x.crossVectors( up, _z ); if ( _x.lengthSq() === 0 ) { // up and z are parallel if ( Math.abs( up.z ) === 1 ) { _z.x += 0.0001; } else { _z.z += 0.0001; } _z.normalize(); _x.crossVectors( up, _z ); } _x.normalize(); _y.crossVectors( _z, _x ); te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x; te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y; te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z; return this; }, multiply: function ( m, n ) { if ( n !== undefined ) { console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' ); return this.multiplyMatrices( m, n ); } return this.multiplyMatrices( this, m ); }, premultiply: function ( m ) { return this.multiplyMatrices( m, this ); }, multiplyMatrices: function ( a, b ) { var ae = a.elements; var be = b.elements; var te = this.elements; var a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ]; var a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ]; var a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ]; var a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ]; var b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ]; var b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ]; var b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ]; var b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ]; te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41; te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42; te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43; te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44; te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41; te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42; te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43; te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44; te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41; te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42; te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43; te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44; te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41; te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42; te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43; te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44; return this; }, multiplyScalar: function ( s ) { var te = this.elements; te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s; te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s; te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s; te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s; return this; }, determinant: function () { var te = this.elements; var n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ]; var n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ]; var n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ]; var n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ]; //TODO: make this more efficient //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm ) return ( n41 * ( + n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34 ) + n42 * ( + n11 * n23 * n34 - n11 * n24 * n33 + n14 * n21 * n33 - n13 * n21 * n34 + n13 * n24 * n31 - n14 * n23 * n31 ) + n43 * ( + n11 * n24 * n32 - n11 * n22 * n34 - n14 * n21 * n32 + n12 * n21 * n34 + n14 * n22 * n31 - n12 * n24 * n31 ) + n44 * ( - n13 * n22 * n31 - n11 * n23 * n32 + n11 * n22 * n33 + n13 * n21 * n32 - n12 * n21 * n33 + n12 * n23 * n31 ) ); }, transpose: function () { var te = this.elements; var tmp; tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp; tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp; tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp; tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp; tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp; tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp; return this; }, setPosition: function ( x, y, z ) { var te = this.elements; if ( x.isVector3 ) { te[ 12 ] = x.x; te[ 13 ] = x.y; te[ 14 ] = x.z; } else { te[ 12 ] = x; te[ 13 ] = y; te[ 14 ] = z; } return this; }, getInverse: function ( m, throwOnDegenerate ) { // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm var te = this.elements, me = m.elements, n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ], n41 = me[ 3 ], n12 = me[ 4 ], n22 = me[ 5 ], n32 = me[ 6 ], n42 = me[ 7 ], n13 = me[ 8 ], n23 = me[ 9 ], n33 = me[ 10 ], n43 = me[ 11 ], n14 = me[ 12 ], n24 = me[ 13 ], n34 = me[ 14 ], n44 = me[ 15 ], t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44, t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44, t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44, t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34; var det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14; if ( det === 0 ) { var msg = "THREE.Matrix4: .getInverse() can't invert matrix, determinant is 0"; if ( throwOnDegenerate === true ) { throw new Error( msg ); } else { console.warn( msg ); } return this.identity(); } var detInv = 1 / det; te[ 0 ] = t11 * detInv; te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv; te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv; te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv; te[ 4 ] = t12 * detInv; te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv; te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv; te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv; te[ 8 ] = t13 * detInv; te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv; te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv; te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv; te[ 12 ] = t14 * detInv; te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv; te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv; te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv; return this; }, scale: function ( v ) { var te = this.elements; var x = v.x, y = v.y, z = v.z; te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z; te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z; te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z; te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z; return this; }, getMaxScaleOnAxis: function () { var te = this.elements; var scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ]; var scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ]; var scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ]; return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) ); }, makeTranslation: function ( x, y, z ) { this.set( 1, 0, 0, x, 0, 1, 0, y, 0, 0, 1, z, 0, 0, 0, 1 ); return this; }, makeRotationX: function ( theta ) { var c = Math.cos( theta ), s = Math.sin( theta ); this.set( 1, 0, 0, 0, 0, c, - s, 0, 0, s, c, 0, 0, 0, 0, 1 ); return this; }, makeRotationY: function ( theta ) { var c = Math.cos( theta ), s = Math.sin( theta ); this.set( c, 0, s, 0, 0, 1, 0, 0, - s, 0, c, 0, 0, 0, 0, 1 ); return this; }, makeRotationZ: function ( theta ) { var c = Math.cos( theta ), s = Math.sin( theta ); this.set( c, - s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ); return this; }, makeRotationAxis: function ( axis, angle ) { // Based on http://www.gamedev.net/reference/articles/article1199.asp var c = Math.cos( angle ); var s = Math.sin( angle ); var t = 1 - c; var x = axis.x, y = axis.y, z = axis.z; var tx = t * x, ty = t * y; this.set( tx * x + c, tx * y - s * z, tx * z + s * y, 0, tx * y + s * z, ty * y + c, ty * z - s * x, 0, tx * z - s * y, ty * z + s * x, t * z * z + c, 0, 0, 0, 0, 1 ); return this; }, makeScale: function ( x, y, z ) { this.set( x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1 ); return this; }, makeShear: function ( x, y, z ) { this.set( 1, y, z, 0, x, 1, z, 0, x, y, 1, 0, 0, 0, 0, 1 ); return this; }, compose: function ( position, quaternion, scale ) { var te = this.elements; var x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w; var x2 = x + x, y2 = y + y, z2 = z + z; var xx = x * x2, xy = x * y2, xz = x * z2; var yy = y * y2, yz = y * z2, zz = z * z2; var wx = w * x2, wy = w * y2, wz = w * z2; var sx = scale.x, sy = scale.y, sz = scale.z; te[ 0 ] = ( 1 - ( yy + zz ) ) * sx; te[ 1 ] = ( xy + wz ) * sx; te[ 2 ] = ( xz - wy ) * sx; te[ 3 ] = 0; te[ 4 ] = ( xy - wz ) * sy; te[ 5 ] = ( 1 - ( xx + zz ) ) * sy; te[ 6 ] = ( yz + wx ) * sy; te[ 7 ] = 0; te[ 8 ] = ( xz + wy ) * sz; te[ 9 ] = ( yz - wx ) * sz; te[ 10 ] = ( 1 - ( xx + yy ) ) * sz; te[ 11 ] = 0; te[ 12 ] = position.x; te[ 13 ] = position.y; te[ 14 ] = position.z; te[ 15 ] = 1; return this; }, decompose: function ( position, quaternion, scale ) { var te = this.elements; var sx = _v1.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length(); var sy = _v1.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length(); var sz = _v1.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length(); // if determine is negative, we need to invert one scale var det = this.determinant(); if ( det < 0 ) { sx = - sx; } position.x = te[ 12 ]; position.y = te[ 13 ]; position.z = te[ 14 ]; // scale the rotation part _m1.copy( this ); var invSX = 1 / sx; var invSY = 1 / sy; var invSZ = 1 / sz; _m1.elements[ 0 ] *= invSX; _m1.elements[ 1 ] *= invSX; _m1.elements[ 2 ] *= invSX; _m1.elements[ 4 ] *= invSY; _m1.elements[ 5 ] *= invSY; _m1.elements[ 6 ] *= invSY; _m1.elements[ 8 ] *= invSZ; _m1.elements[ 9 ] *= invSZ; _m1.elements[ 10 ] *= invSZ; quaternion.setFromRotationMatrix( _m1 ); scale.x = sx; scale.y = sy; scale.z = sz; return this; }, makePerspective: function ( left, right, top, bottom, near, far ) { if ( far === undefined ) { console.warn( 'THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.' ); } var te = this.elements; var x = 2 * near / ( right - left ); var y = 2 * near / ( top - bottom ); var a = ( right + left ) / ( right - left ); var b = ( top + bottom ) / ( top - bottom ); var c = - ( far + near ) / ( far - near ); var d = - 2 * far * near / ( far - near ); te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0; te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0; te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d; te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0; return this; }, makeOrthographic: function ( left, right, top, bottom, near, far ) { var te = this.elements; var w = 1.0 / ( right - left ); var h = 1.0 / ( top - bottom ); var p = 1.0 / ( far - near ); var x = ( right + left ) * w; var y = ( top + bottom ) * h; var z = ( far + near ) * p; te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x; te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y; te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z; te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1; return this; }, equals: function ( matrix ) { var te = this.elements; var me = matrix.elements; for ( var i = 0; i < 16; i ++ ) { if ( te[ i ] !== me[ i ] ) { return false; } } return true; }, fromArray: function ( array, offset ) { if ( offset === undefined ) { offset = 0; } for ( var i = 0; i < 16; i ++ ) { this.elements[ i ] = array[ i + offset ]; } return this; }, toArray: function ( array, offset ) { if ( array === undefined ) { array = []; } if ( offset === undefined ) { offset = 0; } var te = this.elements; array[ offset ] = te[ 0 ]; array[ offset + 1 ] = te[ 1 ]; array[ offset + 2 ] = te[ 2 ]; array[ offset + 3 ] = te[ 3 ]; array[ offset + 4 ] = te[ 4 ]; array[ offset + 5 ] = te[ 5 ]; array[ offset + 6 ] = te[ 6 ]; array[ offset + 7 ] = te[ 7 ]; array[ offset + 8 ] = te[ 8 ]; array[ offset + 9 ] = te[ 9 ]; array[ offset + 10 ] = te[ 10 ]; array[ offset + 11 ] = te[ 11 ]; array[ offset + 12 ] = te[ 12 ]; array[ offset + 13 ] = te[ 13 ]; array[ offset + 14 ] = te[ 14 ]; array[ offset + 15 ] = te[ 15 ]; return array; } } ); /** * @author mrdoob / http://mrdoob.com/ * @author WestLangley / http://github.com/WestLangley * @author bhouston / http://clara.io */ var _matrix = new Matrix4(); var _quaternion$1 = new Quaternion(); function Euler( x, y, z, order ) { this._x = x || 0; this._y = y || 0; this._z = z || 0; this._order = order || Euler.DefaultOrder; } Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ]; Euler.DefaultOrder = 'XYZ'; Object.defineProperties( Euler.prototype, { x: { get: function () { return this._x; }, set: function ( value ) { this._x = value; this._onChangeCallback(); } }, y: { get: function () { return this._y; }, set: function ( value ) { this._y = value; this._onChangeCallback(); } }, z: { get: function () { return this._z; }, set: function ( value ) { this._z = value; this._onChangeCallback(); } }, order: { get: function () { return this._order; }, set: function ( value ) { this._order = value; this._onChangeCallback(); } } } ); Object.assign( Euler.prototype, { isEuler: true, set: function ( x, y, z, order ) { this._x = x; this._y = y; this._z = z; this._order = order || this._order; this._onChangeCallback(); return this; }, clone: function () { return new this.constructor( this._x, this._y, this._z, this._order ); }, copy: function ( euler ) { this._x = euler._x; this._y = euler._y; this._z = euler._z; this._order = euler._order; this._onChangeCallback(); return this; }, setFromRotationMatrix: function ( m, order, update ) { var clamp = MathUtils.clamp; // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) var te = m.elements; var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ]; var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ]; var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ]; order = order || this._order; if ( order === 'XYZ' ) { this._y = Math.asin( clamp( m13, - 1, 1 ) ); if ( Math.abs( m13 ) < 0.9999999 ) { this._x = Math.atan2( - m23, m33 ); this._z = Math.atan2( - m12, m11 ); } else { this._x = Math.atan2( m32, m22 ); this._z = 0; } } else if ( order === 'YXZ' ) { this._x = Math.asin( - clamp( m23, - 1, 1 ) ); if ( Math.abs( m23 ) < 0.9999999 ) { this._y = Math.atan2( m13, m33 ); this._z = Math.atan2( m21, m22 ); } else { this._y = Math.atan2( - m31, m11 ); this._z = 0; } } else if ( order === 'ZXY' ) { this._x = Math.asin( clamp( m32, - 1, 1 ) ); if ( Math.abs( m32 ) < 0.9999999 ) { this._y = Math.atan2( - m31, m33 ); this._z = Math.atan2( - m12, m22 ); } else { this._y = 0; this._z = Math.atan2( m21, m11 ); } } else if ( order === 'ZYX' ) { this._y = Math.asin( - clamp( m31, - 1, 1 ) ); if ( Math.abs( m31 ) < 0.9999999 ) { this._x = Math.atan2( m32, m33 ); this._z = Math.atan2( m21, m11 ); } else { this._x = 0; this._z = Math.atan2( - m12, m22 ); } } else if ( order === 'YZX' ) { this._z = Math.asin( clamp( m21, - 1, 1 ) ); if ( Math.abs( m21 ) < 0.9999999 ) { this._x = Math.atan2( - m23, m22 ); this._y = Math.atan2( - m31, m11 ); } else { this._x = 0; this._y = Math.atan2( m13, m33 ); } } else if ( order === 'XZY' ) { this._z = Math.asin( - clamp( m12, - 1, 1 ) ); if ( Math.abs( m12 ) < 0.9999999 ) { this._x = Math.atan2( m32, m22 ); this._y = Math.atan2( m13, m11 ); } else { this._x = Math.atan2( - m23, m33 ); this._y = 0; } } else { console.warn( 'THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order ); } this._order = order; if ( update !== false ) { this._onChangeCallback(); } return this; }, setFromQuaternion: function ( q, order, update ) { _matrix.makeRotationFromQuaternion( q ); return this.setFromRotationMatrix( _matrix, order, update ); }, setFromVector3: function ( v, order ) { return this.set( v.x, v.y, v.z, order || this._order ); }, reorder: function ( newOrder ) { // WARNING: this discards revolution information -bhouston _quaternion$1.setFromEuler( this ); return this.setFromQuaternion( _quaternion$1, newOrder ); }, equals: function ( euler ) { return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order ); }, fromArray: function ( array ) { this._x = array[ 0 ]; this._y = array[ 1 ]; this._z = array[ 2 ]; if ( array[ 3 ] !== undefined ) { this._order = array[ 3 ]; } this._onChangeCallback(); return this; }, toArray: function ( array, offset ) { if ( array === undefined ) { array = []; } if ( offset === undefined ) { offset = 0; } array[ offset ] = this._x; array[ offset + 1 ] = this._y; array[ offset + 2 ] = this._z; array[ offset + 3 ] = this._order; return array; }, toVector3: function ( optionalResult ) { if ( optionalResult ) { return optionalResult.set( this._x, this._y, this._z ); } else { return new Vector3( this._x, this._y, this._z ); } }, _onChange: function ( callback ) { this._onChangeCallback = callback; return this; }, _onChangeCallback: function () {} } ); /** * @author mrdoob / http://mrdoob.com/ */ function Layers() { this.mask = 1 | 0; } Object.assign( Layers.prototype, { set: function ( channel ) { this.mask = 1 << channel | 0; }, enable: function ( channel ) { this.mask |= 1 << channel | 0; }, enableAll: function () { this.mask = 0xffffffff | 0; }, toggle: function ( channel ) { this.mask ^= 1 << channel | 0; }, disable: function ( channel ) { this.mask &= ~ ( 1 << channel | 0 ); }, disableAll: function () { this.mask = 0; }, test: function ( layers ) { return ( this.mask & layers.mask ) !== 0; } } ); var _object3DId = 0; var _v1$1 = new Vector3(); var _q1 = new Quaternion(); var _m1$1 = new Matrix4(); var _target = new Vector3(); var _position = new Vector3(); var _scale = new Vector3(); var _quaternion$2 = new Quaternion(); var _xAxis = new Vector3( 1, 0, 0 ); var _yAxis = new Vector3( 0, 1, 0 ); var _zAxis = new Vector3( 0, 0, 1 ); var _addedEvent = { type: 'added' }; var _removedEvent = { type: 'removed' }; /** * @author mrdoob / http://mrdoob.com/ * @author mikael emtinger / http://gomo.se/ * @author alteredq / http://alteredqualia.com/ * @author WestLangley / http://github.com/WestLangley * @author elephantatwork / www.elephantatwork.ch */ function Object3D() { Object.defineProperty( this, 'id', { value: _object3DId ++ } ); this.uuid = MathUtils.generateUUID(); this.name = ''; this.type = 'Object3D'; this.parent = null; this.children = []; this.up = Object3D.DefaultUp.clone(); var position = new Vector3(); var rotation = new Euler(); var quaternion = new Quaternion(); var scale = new Vector3( 1, 1, 1 ); function onRotationChange() { quaternion.setFromEuler( rotation, false ); } function onQuaternionChange() { rotation.setFromQuaternion( quaternion, undefined, false ); } rotation._onChange( onRotationChange ); quaternion._onChange( onQuaternionChange ); Object.defineProperties( this, { position: { configurable: true, enumerable: true, value: position }, rotation: { configurable: true, enumerable: true, value: rotation }, quaternion: { configurable: true, enumerable: true, value: quaternion }, scale: { configurable: true, enumerable: true, value: scale }, modelViewMatrix: { value: new Matrix4() }, normalMatrix: { value: new Matrix3() } } ); this.matrix = new Matrix4(); this.matrixWorld = new Matrix4(); this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate; this.matrixWorldNeedsUpdate = false; this.layers = new Layers(); this.visible = true; this.castShadow = false; this.receiveShadow = false; this.frustumCulled = true; this.renderOrder = 0; this.userData = {}; } Object3D.DefaultUp = new Vector3( 0, 1, 0 ); Object3D.DefaultMatrixAutoUpdate = true; Object3D.prototype = Object.assign( Object.create( EventDispatcher.prototype ), { constructor: Object3D, isObject3D: true, onBeforeRender: function () {}, onAfterRender: function () {}, applyMatrix4: function ( matrix ) { if ( this.matrixAutoUpdate ) { this.updateMatrix(); } this.matrix.premultiply( matrix ); this.matrix.decompose( this.position, this.quaternion, this.scale ); }, applyQuaternion: function ( q ) { this.quaternion.premultiply( q ); return this; }, setRotationFromAxisAngle: function ( axis, angle ) { // assumes axis is normalized this.quaternion.setFromAxisAngle( axis, angle ); }, setRotationFromEuler: function ( euler ) { this.quaternion.setFromEuler( euler, true ); }, setRotationFromMatrix: function ( m ) { // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) this.quaternion.setFromRotationMatrix( m ); }, setRotationFromQuaternion: function ( q ) { // assumes q is normalized this.quaternion.copy( q ); }, rotateOnAxis: function ( axis, angle ) { // rotate object on axis in object space // axis is assumed to be normalized _q1.setFromAxisAngle( axis, angle ); this.quaternion.multiply( _q1 ); return this; }, rotateOnWorldAxis: function ( axis, angle ) { // rotate object on axis in world space // axis is assumed to be normalized // method assumes no rotated parent _q1.setFromAxisAngle( axis, angle ); this.quaternion.premultiply( _q1 ); return this; }, rotateX: function ( angle ) { return this.rotateOnAxis( _xAxis, angle ); }, rotateY: function ( angle ) { return this.rotateOnAxis( _yAxis, angle ); }, rotateZ: function ( angle ) { return this.rotateOnAxis( _zAxis, angle ); }, translateOnAxis: function ( axis, distance ) { // translate object by distance along axis in object space // axis is assumed to be normalized _v1$1.copy( axis ).applyQuaternion( this.quaternion ); this.position.add( _v1$1.multiplyScalar( distance ) ); return this; }, translateX: function ( distance ) { return this.translateOnAxis( _xAxis, distance ); }, translateY: function ( distance ) { return this.translateOnAxis( _yAxis, distance ); }, translateZ: function ( distance ) { return this.translateOnAxis( _zAxis, distance ); }, localToWorld: function ( vector ) { return vector.applyMatrix4( this.matrixWorld ); }, worldToLocal: function ( vector ) { return vector.applyMatrix4( _m1$1.getInverse( this.matrixWorld ) ); }, lookAt: function ( x, y, z ) { // This method does not support objects having non-uniformly-scaled parent(s) if ( x.isVector3 ) { _target.copy( x ); } else { _target.set( x, y, z ); } var parent = this.parent; this.updateWorldMatrix( true, false ); _position.setFromMatrixPosition( this.matrixWorld ); if ( this.isCamera || this.isLight ) { _m1$1.lookAt( _position, _target, this.up ); } else { _m1$1.lookAt( _target, _position, this.up ); } this.quaternion.setFromRotationMatrix( _m1$1 ); if ( parent ) { _m1$1.extractRotation( parent.matrixWorld ); _q1.setFromRotationMatrix( _m1$1 ); this.quaternion.premultiply( _q1.inverse() ); } }, add: function ( object ) { if ( arguments.length > 1 ) { for ( var i = 0; i < arguments.length; i ++ ) { this.add( arguments[ i ] ); } return this; } if ( object === this ) { console.error( "THREE.Object3D.add: object can't be added as a child of itself.", object ); return this; } if ( ( object && object.isObject3D ) ) { if ( object.parent !== null ) { object.parent.remove( object ); } object.parent = this; this.children.push( object ); object.dispatchEvent( _addedEvent ); } else { console.error( "THREE.Object3D.add: object not an instance of THREE.Object3D.", object ); } return this; }, remove: function ( object ) { if ( arguments.length > 1 ) { for ( var i = 0; i < arguments.length; i ++ ) { this.remove( arguments[ i ] ); } return this; } var index = this.children.indexOf( object ); if ( index !== - 1 ) { object.parent = null; this.children.splice( index, 1 ); object.dispatchEvent( _removedEvent ); } return this; }, attach: function ( object ) { // adds object as a child of this, while maintaining the object's world transform this.updateWorldMatrix( true, false ); _m1$1.getInverse( this.matrixWorld ); if ( object.parent !== null ) { object.parent.updateWorldMatrix( true, false ); _m1$1.multiply( object.parent.matrixWorld ); } object.applyMatrix4( _m1$1 ); object.updateWorldMatrix( false, false ); this.add( object ); return this; }, getObjectById: function ( id ) { return this.getObjectByProperty( 'id', id ); }, getObjectByName: function ( name ) { return this.getObjectByProperty( 'name', name ); }, getObjectByProperty: function ( name, value ) { if ( this[ name ] === value ) { return this; } for ( var i = 0, l = this.children.length; i < l; i ++ ) { var child = this.children[ i ]; var object = child.getObjectByProperty( name, value ); if ( object !== undefined ) { return object; } } return undefined; }, getWorldPosition: function ( target ) { if ( target === undefined ) { console.warn( 'THREE.Object3D: .getWorldPosition() target is now required' ); target = new Vector3(); } this.updateMatrixWorld( true ); return target.setFromMatrixPosition( this.matrixWorld ); }, getWorldQuaternion: function ( target ) { if ( target === undefined ) { console.warn( 'THREE.Object3D: .getWorldQuaternion() target is now required' ); target = new Quaternion(); } this.updateMatrixWorld( true ); this.matrixWorld.decompose( _position, target, _scale ); return target; }, getWorldScale: function ( target ) { if ( target === undefined ) { console.warn( 'THREE.Object3D: .getWorldScale() target is now required' ); target = new Vector3(); } this.updateMatrixWorld( true ); this.matrixWorld.decompose( _position, _quaternion$2, target ); return target; }, getWorldDirection: function ( target ) { if ( target === undefined ) { console.warn( 'THREE.Object3D: .getWorldDirection() target is now required' ); target = new Vector3(); } this.updateMatrixWorld( true ); var e = this.matrixWorld.elements; return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize(); }, raycast: function () {}, traverse: function ( callback ) { callback( this ); var children = this.children; for ( var i = 0, l = children.length; i < l; i ++ ) { children[ i ].traverse( callback ); } }, traverseVisible: function ( callback ) { if ( this.visible === false ) { return; } callback( this ); var children = this.children; for ( var i = 0, l = children.length; i < l; i ++ ) { children[ i ].traverseVisible( callback ); } }, traverseAncestors: function ( callback ) { var parent = this.parent; if ( parent !== null ) { callback( parent ); parent.traverseAncestors( callback ); } }, updateMatrix: function () { this.matrix.compose( this.position, this.quaternion, this.scale ); this.matrixWorldNeedsUpdate = true; }, updateMatrixWorld: function ( force ) { if ( this.matrixAutoUpdate ) { this.updateMatrix(); } if ( this.matrixWorldNeedsUpdate || force ) { if ( this.parent === null ) { this.matrixWorld.copy( this.matrix ); } else { this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix ); } this.matrixWorldNeedsUpdate = false; force = true; } // update children var children = this.children; for ( var i = 0, l = children.length; i < l; i ++ ) { children[ i ].updateMatrixWorld( force ); } }, updateWorldMatrix: function ( updateParents, updateChildren ) { var parent = this.parent; if ( updateParents === true && parent !== null ) { parent.updateWorldMatrix( true, false ); } if ( this.matrixAutoUpdate ) { this.updateMatrix(); } if ( this.parent === null ) { this.matrixWorld.copy( this.matrix ); } else { this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix ); } // update children if ( updateChildren === true ) { var children = this.children; for ( var i = 0, l = children.length; i < l; i ++ ) { children[ i ].updateWorldMatrix( false, true ); } } }, toJSON: function ( meta ) { // meta is a string when called from JSON.stringify var isRootObject = ( meta === undefined || typeof meta === 'string' ); var output = {}; // meta is a hash used to collect geometries, materials. // not providing it implies that this is the root object // being serialized. if ( isRootObject ) { // initialize meta obj meta = { geometries: {}, materials: {}, textures: {}, images: {}, shapes: {} }; output.metadata = { version: 4.5, type: 'Object', generator: 'Object3D.toJSON' }; } // standard Object3D serialization var object = {}; object.uuid = this.uuid; object.type = this.type; if ( this.name !== '' ) { object.name = this.name; } if ( this.castShadow === true ) { object.castShadow = true; } if ( this.receiveShadow === true ) { object.receiveShadow = true; } if ( this.visible === false ) { object.visible = false; } if ( this.frustumCulled === false ) { object.frustumCulled = false; } if ( this.renderOrder !== 0 ) { object.renderOrder = this.renderOrder; } if ( JSON.stringify( this.userData ) !== '{}' ) { object.userData = this.userData; } object.layers = this.layers.mask; object.matrix = this.matrix.toArray(); if ( this.matrixAutoUpdate === false ) { object.matrixAutoUpdate = false; } // object specific properties if ( this.isInstancedMesh ) { object.type = 'InstancedMesh'; object.count = this.count; object.instanceMatrix = this.instanceMatrix.toJSON(); } // function serialize( library, element ) { if ( library[ element.uuid ] === undefined ) { library[ element.uuid ] = element.toJSON( meta ); } return element.uuid; } if ( this.isMesh || this.isLine || this.isPoints ) { object.geometry = serialize( meta.geometries, this.geometry ); var parameters = this.geometry.parameters; if ( parameters !== undefined && parameters.shapes !== undefined ) { var shapes = parameters.shapes; if ( Array.isArray( shapes ) ) { for ( var i = 0, l = shapes.length; i < l; i ++ ) { var shape = shapes[ i ]; serialize( meta.shapes, shape ); } } else { serialize( meta.shapes, shapes ); } } } if ( this.material !== undefined ) { if ( Array.isArray( this.material ) ) { var uuids = []; for ( var i = 0, l = this.material.length; i < l; i ++ ) { uuids.push( serialize( meta.materials, this.material[ i ] ) ); } object.material = uuids; } else { object.material = serialize( meta.materials, this.material ); } } // if ( this.children.length > 0 ) { object.children = []; for ( var i = 0; i < this.children.length; i ++ ) { object.children.push( this.children[ i ].toJSON( meta ).object ); } } if ( isRootObject ) { var geometries = extractFromCache( meta.geometries ); var materials = extractFromCache( meta.materials ); var textures = extractFromCache( meta.textures ); var images = extractFromCache( meta.images ); var shapes = extractFromCache( meta.shapes ); if ( geometries.length > 0 ) { output.geometries = geometries; } if ( materials.length > 0 ) { output.materials = materials; } if ( textures.length > 0 ) { output.textures = textures; } if ( images.length > 0 ) { output.images = images; } if ( shapes.length > 0 ) { output.shapes = shapes; } } output.object = object; return output; // extract data from the cache hash // remove metadata on each item // and return as array function extractFromCache( cache ) { var values = []; for ( var key in cache ) { var data = cache[ key ]; delete data.metadata; values.push( data ); } return values; } }, clone: function ( recursive ) { return new this.constructor().copy( this, recursive ); }, copy: function ( source, recursive ) { if ( recursive === undefined ) { recursive = true; } this.name = source.name; this.up.copy( source.up ); this.position.copy( source.position ); this.quaternion.copy( source.quaternion ); this.scale.copy( source.scale ); this.matrix.copy( source.matrix ); this.matrixWorld.copy( source.matrixWorld ); this.matrixAutoUpdate = source.matrixAutoUpdate; this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate; this.layers.mask = source.layers.mask; this.visible = source.visible; this.castShadow = source.castShadow; this.receiveShadow = source.receiveShadow; this.frustumCulled = source.frustumCulled; this.renderOrder = source.renderOrder; this.userData = JSON.parse( JSON.stringify( source.userData ) ); if ( recursive === true ) { for ( var i = 0; i < source.children.length; i ++ ) { var child = source.children[ i ]; this.add( child.clone() ); } } return this; } } ); /** * @author mrdoob / http://mrdoob.com/ */ function Scene() { Object3D.call( this ); this.type = 'Scene'; this.background = null; this.environment = null; this.fog = null; this.overrideMaterial = null; this.autoUpdate = true; // checked by the renderer if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) { __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) ); // eslint-disable-line no-undef } } Scene.prototype = Object.assign( Object.create( Object3D.prototype ), { constructor: Scene, isScene: true, copy: function ( source, recursive ) { Object3D.prototype.copy.call( this, source, recursive ); if ( source.background !== null ) { this.background = source.background.clone(); } if ( source.environment !== null ) { this.environment = source.environment.clone(); } if ( source.fog !== null ) { this.fog = source.fog.clone(); } if ( source.overrideMaterial !== null ) { this.overrideMaterial = source.overrideMaterial.clone(); } this.autoUpdate = source.autoUpdate; this.matrixAutoUpdate = source.matrixAutoUpdate; return this; }, toJSON: function ( meta ) { var data = Object3D.prototype.toJSON.call( this, meta ); if ( this.background !== null ) { data.object.background = this.background.toJSON( meta ); } if ( this.environment !== null ) { data.object.environment = this.environment.toJSON( meta ); } if ( this.fog !== null ) { data.object.fog = this.fog.toJSON(); } return data; }, dispose: function () { this.dispatchEvent( { type: 'dispose' } ); } } ); var _points = [ new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3() ]; var _vector$1 = new Vector3(); var _box = new Box3(); // triangle centered vertices var _v0 = new Vector3(); var _v1$2 = new Vector3(); var _v2 = new Vector3(); // triangle edge vectors var _f0 = new Vector3(); var _f1 = new Vector3(); var _f2 = new Vector3(); var _center = new Vector3(); var _extents = new Vector3(); var _triangleNormal = new Vector3(); var _testAxis = new Vector3(); /** * @author bhouston / http://clara.io * @author WestLangley / http://github.com/WestLangley */ function Box3( min, max ) { this.min = ( min !== undefined ) ? min : new Vector3( + Infinity, + Infinity, + Infinity ); this.max = ( max !== undefined ) ? max : new Vector3( - Infinity, - Infinity, - Infinity ); } Object.assign( Box3.prototype, { isBox3: true, set: function ( min, max ) { this.min.copy( min ); this.max.copy( max ); return this; }, setFromArray: function ( array ) { var minX = + Infinity; var minY = + Infinity; var minZ = + Infinity; var maxX = - Infinity; var maxY = - Infinity; var maxZ = - Infinity; for ( var i = 0, l = array.length; i < l; i += 3 ) { var x = array[ i ]; var y = array[ i + 1 ]; var z = array[ i + 2 ]; if ( x < minX ) { minX = x; } if ( y < minY ) { minY = y; } if ( z < minZ ) { minZ = z; } if ( x > maxX ) { maxX = x; } if ( y > maxY ) { maxY = y; } if ( z > maxZ ) { maxZ = z; } } this.min.set( minX, minY, minZ ); this.max.set( maxX, maxY, maxZ ); return this; }, setFromBufferAttribute: function ( attribute ) { var minX = + Infinity; var minY = + Infinity; var minZ = + Infinity; var maxX = - Infinity; var maxY = - Infinity; var maxZ = - Infinity; for ( var i = 0, l = attribute.count; i < l; i ++ ) { var x = attribute.getX( i ); var y = attribute.getY( i ); var z = attribute.getZ( i ); if ( x < minX ) { minX = x; } if ( y < minY ) { minY = y; } if ( z < minZ ) { minZ = z; } if ( x > maxX ) { maxX = x; } if ( y > maxY ) { maxY = y; } if ( z > maxZ ) { maxZ = z; } } this.min.set( minX, minY, minZ ); this.max.set( maxX, maxY, maxZ ); return this; }, setFromPoints: function ( points ) { this.makeEmpty(); for ( var i = 0, il = points.length; i < il; i ++ ) { this.expandByPoint( points[ i ] ); } return this; }, setFromCenterAndSize: function ( center, size ) { var halfSize = _vector$1.copy( size ).multiplyScalar( 0.5 ); this.min.copy( center ).sub( halfSize ); this.max.copy( center ).add( halfSize ); return this; }, setFromObject: function ( object ) { this.makeEmpty(); return this.expandByObject( object ); }, clone: function () { return new this.constructor().copy( this ); }, copy: function ( box ) { this.min.copy( box.min ); this.max.copy( box.max ); return this; }, makeEmpty: function () { this.min.x = this.min.y = this.min.z = + Infinity; this.max.x = this.max.y = this.max.z = - Infinity; return this; }, isEmpty: function () { // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z ); }, getCenter: function ( target ) { if ( target === undefined ) { console.warn( 'THREE.Box3: .getCenter() target is now required' ); target = new Vector3(); } return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 ); }, getSize: function ( target ) { if ( target === undefined ) { console.warn( 'THREE.Box3: .getSize() target is now required' ); target = new Vector3(); } return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min ); }, expandByPoint: function ( point ) { this.min.min( point ); this.max.max( point ); return this; }, expandByVector: function ( vector ) { this.min.sub( vector ); this.max.add( vector ); return this; }, expandByScalar: function ( scalar ) { this.min.addScalar( - scalar ); this.max.addScalar( scalar ); return this; }, expandByObject: function ( object ) { // Computes the world-axis-aligned bounding box of an object (including its children), // accounting for both the object's, and children's, world transforms object.updateWorldMatrix( false, false ); var geometry = object.geometry; if ( geometry !== undefined ) { if ( geometry.boundingBox === null ) { geometry.computeBoundingBox(); } _box.copy( geometry.boundingBox ); _box.applyMatrix4( object.matrixWorld ); this.expandByPoint( _box.min ); this.expandByPoint( _box.max ); } var children = object.children; for ( var i = 0, l = children.length; i < l; i ++ ) { this.expandByObject( children[ i ] ); } return this; }, containsPoint: function ( point ) { return point.x < this.min.x || point.x > this.max.x || point.y < this.min.y || point.y > this.max.y || point.z < this.min.z || point.z > this.max.z ? false : true; }, containsBox: function ( box ) { return this.min.x <= box.min.x && box.max.x <= this.max.x && this.min.y <= box.min.y && box.max.y <= this.max.y && this.min.z <= box.min.z && box.max.z <= this.max.z; }, getParameter: function ( point, target ) { // This can potentially have a divide by zero if the box // has a size dimension of 0. if ( target === undefined ) { console.warn( 'THREE.Box3: .getParameter() target is now required' ); target = new Vector3(); } return target.set( ( point.x - this.min.x ) / ( this.max.x - this.min.x ), ( point.y - this.min.y ) / ( this.max.y - this.min.y ), ( point.z - this.min.z ) / ( this.max.z - this.min.z ) ); }, intersectsBox: function ( box ) { // using 6 splitting planes to rule out intersections. return box.max.x < this.min.x || box.min.x > this.max.x || box.max.y < this.min.y || box.min.y > this.max.y || box.max.z < this.min.z || box.min.z > this.max.z ? false : true; }, intersectsSphere: function ( sphere ) { // Find the point on the AABB closest to the sphere center. this.clampPoint( sphere.center, _vector$1 ); // If that point is inside the sphere, the AABB and sphere intersect. return _vector$1.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius ); }, intersectsPlane: function ( plane ) { // We compute the minimum and maximum dot product values. If those values // are on the same side (back or front) of the plane, then there is no intersection. var min, max; if ( plane.normal.x > 0 ) { min = plane.normal.x * this.min.x; max = plane.normal.x * this.max.x; } else { min = plane.normal.x * this.max.x; max = plane.normal.x * this.min.x; } if ( plane.normal.y > 0 ) { min += plane.normal.y * this.min.y; max += plane.normal.y * this.max.y; } else { min += plane.normal.y * this.max.y; max += plane.normal.y * this.min.y; } if ( plane.normal.z > 0 ) { min += plane.normal.z * this.min.z; max += plane.normal.z * this.max.z; } else { min += plane.normal.z * this.max.z; max += plane.normal.z * this.min.z; } return ( min <= - plane.constant && max >= - plane.constant ); }, intersectsTriangle: function ( triangle ) { if ( this.isEmpty() ) { return false; } // compute box center and extents this.getCenter( _center ); _extents.subVectors( this.max, _center ); // translate triangle to aabb origin _v0.subVectors( triangle.a, _center ); _v1$2.subVectors( triangle.b, _center ); _v2.subVectors( triangle.c, _center ); // compute edge vectors for triangle _f0.subVectors( _v1$2, _v0 ); _f1.subVectors( _v2, _v1$2 ); _f2.subVectors( _v0, _v2 ); // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb // make an axis testing of each of the 3 sides of the aabb against each of the 3 sides of the triangle = 9 axis of separation // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned) var axes = [ 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y, _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x, - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0 ]; if ( ! satForAxes( axes, _v0, _v1$2, _v2, _extents ) ) { return false; } // test 3 face normals from the aabb axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ]; if ( ! satForAxes( axes, _v0, _v1$2, _v2, _extents ) ) { return false; } // finally testing the face normal of the triangle // use already existing triangle edge vectors here _triangleNormal.crossVectors( _f0, _f1 ); axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ]; return satForAxes( axes, _v0, _v1$2, _v2, _extents ); }, clampPoint: function ( point, target ) { if ( target === undefined ) { console.warn( 'THREE.Box3: .clampPoint() target is now required' ); target = new Vector3(); } return target.copy( point ).clamp( this.min, this.max ); }, distanceToPoint: function ( point ) { var clampedPoint = _vector$1.copy( point ).clamp( this.min, this.max ); return clampedPoint.sub( point ).length(); }, getBoundingSphere: function ( target ) { if ( target === undefined ) { console.error( 'THREE.Box3: .getBoundingSphere() target is now required' ); //target = new Sphere(); // removed to avoid cyclic dependency } this.getCenter( target.center ); target.radius = this.getSize( _vector$1 ).length() * 0.5; return target; }, intersect: function ( box ) { this.min.max( box.min ); this.max.min( box.max ); // ensure that if there is no overlap, the result is fully empty, not slightly empty with non-inf/+inf values that will cause subsequence intersects to erroneously return valid values. if ( this.isEmpty() ) { this.makeEmpty(); } return this; }, union: function ( box ) { this.min.min( box.min ); this.max.max( box.max ); return this; }, applyMatrix4: function ( matrix ) { // transform of empty box is an empty box. if ( this.isEmpty() ) { return this; } // NOTE: I am using a binary pattern to specify all 2^3 combinations below _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000 _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001 _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010 _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011 _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100 _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101 _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110 _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111 this.setFromPoints( _points ); return this; }, translate: function ( offset ) { this.min.add( offset ); this.max.add( offset ); return this; }, equals: function ( box ) { return box.min.equals( this.min ) && box.max.equals( this.max ); } } ); function satForAxes( axes, v0, v1, v2, extents ) { var i, j; for ( i = 0, j = axes.length - 3; i <= j; i += 3 ) { _testAxis.fromArray( axes, i ); // project the aabb onto the seperating axis var r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z ); // project all 3 vertices of the triangle onto the seperating axis var p0 = v0.dot( _testAxis ); var p1 = v1.dot( _testAxis ); var p2 = v2.dot( _testAxis ); // actual test, basically see if either of the most extreme of the triangle points intersects r if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) { // points of the projected triangle are outside the projected half-length of the aabb // the axis is seperating and we can exit return false; } } return true; } var _box$1 = new Box3(); /** * @author bhouston / http://clara.io * @author mrdoob / http://mrdoob.com/ */ function Sphere( center, radius ) { this.center = ( center !== undefined ) ? center : new Vector3(); this.radius = ( radius !== undefined ) ? radius : 0; } Object.assign( Sphere.prototype, { set: function ( center, radius ) { this.center.copy( center ); this.radius = radius; return this; }, setFromPoints: function ( points, optionalCenter ) { var center = this.center; if ( optionalCenter !== undefined ) { center.copy( optionalCenter ); } else { _box$1.setFromPoints( points ).getCenter( center ); } var maxRadiusSq = 0; for ( var i = 0, il = points.length; i < il; i ++ ) { maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) ); } this.radius = Math.sqrt( maxRadiusSq ); return this; }, clone: function () { return new this.constructor().copy( this ); }, copy: function ( sphere ) { this.center.copy( sphere.center ); this.radius = sphere.radius; return this; }, empty: function () { return ( this.radius <= 0 ); }, containsPoint: function ( point ) { return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) ); }, distanceToPoint: function ( point ) { return ( point.distanceTo( this.center ) - this.radius ); }, intersectsSphere: function ( sphere ) { var radiusSum = this.radius + sphere.radius; return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum ); }, intersectsBox: function ( box ) { return box.intersectsSphere( this ); }, intersectsPlane: function ( plane ) { return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius; }, clampPoint: function ( point, target ) { var deltaLengthSq = this.center.distanceToSquared( point ); if ( target === undefined ) { console.warn( 'THREE.Sphere: .clampPoint() target is now required' ); target = new Vector3(); } target.copy( point ); if ( deltaLengthSq > ( this.radius * this.radius ) ) { target.sub( this.center ).normalize(); target.multiplyScalar( this.radius ).add( this.center ); } return target; }, getBoundingBox: function ( target ) { if ( target === undefined ) { console.warn( 'THREE.Sphere: .getBoundingBox() target is now required' ); target = new Box3(); } target.set( this.center, this.center ); target.expandByScalar( this.radius ); return target; }, applyMatrix4: function ( matrix ) { this.center.applyMatrix4( matrix ); this.radius = this.radius * matrix.getMaxScaleOnAxis(); return this; }, translate: function ( offset ) { this.center.add( offset ); return this; }, equals: function ( sphere ) { return sphere.center.equals( this.center ) && ( sphere.radius === this.radius ); } } ); var _vector$2 = new Vector3(); var _segCenter = new Vector3(); var _segDir = new Vector3(); var _diff = new Vector3(); var _edge1 = new Vector3(); var _edge2 = new Vector3(); var _normal = new Vector3(); /** * @author bhouston / http://clara.io */ function Ray( origin, direction ) { this.origin = ( origin !== undefined ) ? origin : new Vector3(); this.direction = ( direction !== undefined ) ? direction : new Vector3( 0, 0, - 1 ); } Object.assign( Ray.prototype, { set: function ( origin, direction ) { this.origin.copy( origin ); this.direction.copy( direction ); return this; }, clone: function () { return new this.constructor().copy( this ); }, copy: function ( ray ) { this.origin.copy( ray.origin ); this.direction.copy( ray.direction ); return this; }, at: function ( t, target ) { if ( target === undefined ) { console.warn( 'THREE.Ray: .at() target is now required' ); target = new Vector3(); } return target.copy( this.direction ).multiplyScalar( t ).add( this.origin ); }, lookAt: function ( v ) { this.direction.copy( v ).sub( this.origin ).normalize(); return this; }, recast: function ( t ) { this.origin.copy( this.at( t, _vector$2 ) ); return this; }, closestPointToPoint: function ( point, target ) { if ( target === undefined ) { console.warn( 'THREE.Ray: .closestPointToPoint() target is now required' ); target = new Vector3(); } target.subVectors( point, this.origin ); var directionDistance = target.dot( this.direction ); if ( directionDistance < 0 ) { return target.copy( this.origin ); } return target.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin ); }, distanceToPoint: function ( point ) { return Math.sqrt( this.distanceSqToPoint( point ) ); }, distanceSqToPoint: function ( point ) { var directionDistance = _vector$2.subVectors( point, this.origin ).dot( this.direction ); // point behind the ray if ( directionDistance < 0 ) { return this.origin.distanceToSquared( point ); } _vector$2.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin ); return _vector$2.distanceToSquared( point ); }, distanceSqToSegment: function ( v0, v1, optionalPointOnRay, optionalPointOnSegment ) { // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h // It returns the min distance between the ray and the segment // defined by v0 and v1 // It can also set two optional targets : // - The closest point on the ray // - The closest point on the segment _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 ); _segDir.copy( v1 ).sub( v0 ).normalize(); _diff.copy( this.origin ).sub( _segCenter ); var segExtent = v0.distanceTo( v1 ) * 0.5; var a01 = - this.direction.dot( _segDir ); var b0 = _diff.dot( this.direction ); var b1 = - _diff.dot( _segDir ); var c = _diff.lengthSq(); var det = Math.abs( 1 - a01 * a01 ); var s0, s1, sqrDist, extDet; if ( det > 0 ) { // The ray and segment are not parallel. s0 = a01 * b1 - b0; s1 = a01 * b0 - b1; extDet = segExtent * det; if ( s0 >= 0 ) { if ( s1 >= - extDet ) { if ( s1 <= extDet ) { // region 0 // Minimum at interior points of ray and segment. var invDet = 1 / det; s0 *= invDet; s1 *= invDet; sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c; } else { // region 1 s1 = segExtent; s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; } } else { // region 5 s1 = - segExtent; s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; } } else { if ( s1 <= - extDet ) { // region 4 s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) ); s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent ); sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; } else if ( s1 <= extDet ) { // region 3 s0 = 0; s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent ); sqrDist = s1 * ( s1 + 2 * b1 ) + c; } else { // region 2 s0 = Math.max( 0, - ( a01 * segExtent + b0 ) ); s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent ); sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; } } } else { // Ray and segment are parallel. s1 = ( a01 > 0 ) ? - segExtent : segExtent; s0 = Math.max( 0, - ( a01 * s1 + b0 ) ); sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c; } if ( optionalPointOnRay ) { optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin ); } if ( optionalPointOnSegment ) { optionalPointOnSegment.copy( _segDir ).multiplyScalar( s1 ).add( _segCenter ); } return sqrDist; }, intersectSphere: function ( sphere, target ) { _vector$2.subVectors( sphere.center, this.origin ); var tca = _vector$2.dot( this.direction ); var d2 = _vector$2.dot( _vector$2 ) - tca * tca; var radius2 = sphere.radius * sphere.radius; if ( d2 > radius2 ) { return null; } var thc = Math.sqrt( radius2 - d2 ); // t0 = first intersect point - entrance on front of sphere var t0 = tca - thc; // t1 = second intersect point - exit point on back of sphere var t1 = tca + thc; // test to see if both t0 and t1 are behind the ray - if so, return null if ( t0 < 0 && t1 < 0 ) { return null; } // test to see if t0 is behind the ray: // if it is, the ray is inside the sphere, so return the second exit point scaled by t1, // in order to always return an intersect point that is in front of the ray. if ( t0 < 0 ) { return this.at( t1, target ); } // else t0 is in front of the ray, so return the first collision point scaled by t0 return this.at( t0, target ); }, intersectsSphere: function ( sphere ) { return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius ); }, distanceToPlane: function ( plane ) { var denominator = plane.normal.dot( this.direction ); if ( denominator === 0 ) { // line is coplanar, return origin if ( plane.distanceToPoint( this.origin ) === 0 ) { return 0; } // Null is preferable to undefined since undefined means.... it is undefined return null; } var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator; // Return if the ray never intersects the plane return t >= 0 ? t : null; }, intersectPlane: function ( plane, target ) { var t = this.distanceToPlane( plane ); if ( t === null ) { return null; } return this.at( t, target ); }, intersectsPlane: function ( plane ) { // check if the ray lies on the plane first var distToPoint = plane.distanceToPoint( this.origin ); if ( distToPoint === 0 ) { return true; } var denominator = plane.normal.dot( this.direction ); if ( denominator * distToPoint < 0 ) { return true; } // ray origin is behind the plane (and is pointing behind it) return false; }, intersectBox: function ( box, target ) { var tmin, tmax, tymin, tymax, tzmin, tzmax; var invdirx = 1 / this.direction.x, invdiry = 1 / this.direction.y, invdirz = 1 / this.direction.z; var origin = this.origin; if ( invdirx >= 0 ) { tmin = ( box.min.x - origin.x ) * invdirx; tmax = ( box.max.x - origin.x ) * invdirx; } else { tmin = ( box.max.x - origin.x ) * invdirx; tmax = ( box.min.x - origin.x ) * invdirx; } if ( invdiry >= 0 ) { tymin = ( box.min.y - origin.y ) * invdiry; tymax = ( box.max.y - origin.y ) * invdiry; } else { tymin = ( box.max.y - origin.y ) * invdiry; tymax = ( box.min.y - origin.y ) * invdiry; } if ( ( tmin > tymax ) || ( tymin > tmax ) ) { return null; } // These lines also handle the case where tmin or tmax is NaN // (result of 0 * Infinity). x !== x returns true if x is NaN if ( tymin > tmin || tmin !== tmin ) { tmin = tymin; } if ( tymax < tmax || tmax !== tmax ) { tmax = tymax; } if ( invdirz >= 0 ) { tzmin = ( box.min.z - origin.z ) * invdirz; tzmax = ( box.max.z - origin.z ) * invdirz; } else { tzmin = ( box.max.z - origin.z ) * invdirz; tzmax = ( box.min.z - origin.z ) * invdirz; } if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) { return null; } if ( tzmin > tmin || tmin !== tmin ) { tmin = tzmin; } if ( tzmax < tmax || tmax !== tmax ) { tmax = tzmax; } //return point closest to the ray (positive side) if ( tmax < 0 ) { return null; } return this.at( tmin >= 0 ? tmin : tmax, target ); }, intersectsBox: function ( box ) { return this.intersectBox( box, _vector$2 ) !== null; }, intersectTriangle: function ( a, b, c, backfaceCulling, target ) { // Compute the offset origin, edges, and normal. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h _edge1.subVectors( b, a ); _edge2.subVectors( c, a ); _normal.crossVectors( _edge1, _edge2 ); // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction, // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2)) // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q)) // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N) var DdN = this.direction.dot( _normal ); var sign; if ( DdN > 0 ) { if ( backfaceCulling ) { return null; } sign = 1; } else if ( DdN < 0 ) { sign = - 1; DdN = - DdN; } else { return null; } _diff.subVectors( this.origin, a ); var DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) ); // b1 < 0, no intersection if ( DdQxE2 < 0 ) { return null; } var DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) ); // b2 < 0, no intersection if ( DdE1xQ < 0 ) { return null; } // b1+b2 > 1, no intersection if ( DdQxE2 + DdE1xQ > DdN ) { return null; } // Line intersects triangle, check if ray does. var QdN = - sign * _diff.dot( _normal ); // t < 0, no intersection if ( QdN < 0 ) { return null; } // Ray intersects triangle. return this.at( QdN / DdN, target ); }, applyMatrix4: function ( matrix4 ) { this.origin.applyMatrix4( matrix4 ); this.direction.transformDirection( matrix4 ); return this; }, equals: function ( ray ) { return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction ); } } ); /** * @author bhouston / http://clara.io */ var _vector1 = new Vector3(); var _vector2 = new Vector3(); var _normalMatrix = new Matrix3(); function Plane( normal, constant ) { // normal is assumed to be normalized this.normal = ( normal !== undefined ) ? normal : new Vector3( 1, 0, 0 ); this.constant = ( constant !== undefined ) ? constant : 0; } Object.assign( Plane.prototype, { isPlane: true, set: function ( normal, constant ) { this.normal.copy( normal ); this.constant = constant; return this; }, setComponents: function ( x, y, z, w ) { this.normal.set( x, y, z ); this.constant = w; return this; }, setFromNormalAndCoplanarPoint: function ( normal, point ) { this.normal.copy( normal ); this.constant = - point.dot( this.normal ); return this; }, setFromCoplanarPoints: function ( a, b, c ) { var normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize(); // Q: should an error be thrown if normal is zero (e.g. degenerate plane)? this.setFromNormalAndCoplanarPoint( normal, a ); return this; }, clone: function () { return new this.constructor().copy( this ); }, copy: function ( plane ) { this.normal.copy( plane.normal ); this.constant = plane.constant; return this; }, normalize: function () { // Note: will lead to a divide by zero if the plane is invalid. var inverseNormalLength = 1.0 / this.normal.length(); this.normal.multiplyScalar( inverseNormalLength ); this.constant *= inverseNormalLength; return this; }, negate: function () { this.constant *= - 1; this.normal.negate(); return this; }, distanceToPoint: function ( point ) { return this.normal.dot( point ) + this.constant; }, distanceToSphere: function ( sphere ) { return this.distanceToPoint( sphere.center ) - sphere.radius; }, projectPoint: function ( point, target ) { if ( target === undefined ) { console.warn( 'THREE.Plane: .projectPoint() target is now required' ); target = new Vector3(); } return target.copy( this.normal ).multiplyScalar( - this.distanceToPoint( point ) ).add( point ); }, intersectLine: function ( line, target ) { if ( target === undefined ) { console.warn( 'THREE.Plane: .intersectLine() target is now required' ); target = new Vector3(); } var direction = line.delta( _vector1 ); var denominator = this.normal.dot( direction ); if ( denominator === 0 ) { // line is coplanar, return origin if ( this.distanceToPoint( line.start ) === 0 ) { return target.copy( line.start ); } // Unsure if this is the correct method to handle this case. return undefined; } var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator; if ( t < 0 || t > 1 ) { return undefined; } return target.copy( direction ).multiplyScalar( t ).add( line.start ); }, intersectsLine: function ( line ) { // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it. var startSign = this.distanceToPoint( line.start ); var endSign = this.distanceToPoint( line.end ); return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 ); }, intersectsBox: function ( box ) { return box.intersectsPlane( this ); }, intersectsSphere: function ( sphere ) { return sphere.intersectsPlane( this ); }, coplanarPoint: function ( target ) { if ( target === undefined ) { console.warn( 'THREE.Plane: .coplanarPoint() target is now required' ); target = new Vector3(); } return target.copy( this.normal ).multiplyScalar( - this.constant ); }, applyMatrix4: function ( matrix, optionalNormalMatrix ) { var normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix ); var referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix ); var normal = this.normal.applyMatrix3( normalMatrix ).normalize(); this.constant = - referencePoint.dot( normal ); return this; }, translate: function ( offset ) { this.constant -= offset.dot( this.normal ); return this; }, equals: function ( plane ) { return plane.normal.equals( this.normal ) && ( plane.constant === this.constant ); } } ); /** * @author bhouston / http://clara.io * @author mrdoob / http://mrdoob.com/ */ var _v0$1 = new Vector3(); var _v1$3 = new Vector3(); var _v2$1 = new Vector3(); var _v3 = new Vector3(); var _vab = new Vector3(); var _vac = new Vector3(); var _vbc = new Vector3(); var _vap = new Vector3(); var _vbp = new Vector3(); var _vcp = new Vector3(); function Triangle( a, b, c ) { this.a = ( a !== undefined ) ? a : new Vector3(); this.b = ( b !== undefined ) ? b : new Vector3(); this.c = ( c !== undefined ) ? c : new Vector3(); } Object.assign( Triangle, { getNormal: function ( a, b, c, target ) { if ( target === undefined ) { console.warn( 'THREE.Triangle: .getNormal() target is now required' ); target = new Vector3(); } target.subVectors( c, b ); _v0$1.subVectors( a, b ); target.cross( _v0$1 ); var targetLengthSq = target.lengthSq(); if ( targetLengthSq > 0 ) { return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) ); } return target.set( 0, 0, 0 ); }, // static/instance method to calculate barycentric coordinates // based on: http://www.blackpawn.com/texts/pointinpoly/default.html getBarycoord: function ( point, a, b, c, target ) { _v0$1.subVectors( c, a ); _v1$3.subVectors( b, a ); _v2$1.subVectors( point, a ); var dot00 = _v0$1.dot( _v0$1 ); var dot01 = _v0$1.dot( _v1$3 ); var dot02 = _v0$1.dot( _v2$1 ); var dot11 = _v1$3.dot( _v1$3 ); var dot12 = _v1$3.dot( _v2$1 ); var denom = ( dot00 * dot11 - dot01 * dot01 ); if ( target === undefined ) { console.warn( 'THREE.Triangle: .getBarycoord() target is now required' ); target = new Vector3(); } // collinear or singular triangle if ( denom === 0 ) { // arbitrary location outside of triangle? // not sure if this is the best idea, maybe should be returning undefined return target.set( - 2, - 1, - 1 ); } var invDenom = 1 / denom; var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom; var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom; // barycentric coordinates must always sum to 1 return target.set( 1 - u - v, v, u ); }, containsPoint: function ( point, a, b, c ) { Triangle.getBarycoord( point, a, b, c, _v3 ); return ( _v3.x >= 0 ) && ( _v3.y >= 0 ) && ( ( _v3.x + _v3.y ) <= 1 ); }, getUV: function ( point, p1, p2, p3, uv1, uv2, uv3, target ) { this.getBarycoord( point, p1, p2, p3, _v3 ); target.set( 0, 0 ); target.addScaledVector( uv1, _v3.x ); target.addScaledVector( uv2, _v3.y ); target.addScaledVector( uv3, _v3.z ); return target; }, isFrontFacing: function ( a, b, c, direction ) { _v0$1.subVectors( c, b ); _v1$3.subVectors( a, b ); // strictly front facing return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false; } } ); Object.assign( Triangle.prototype, { set: function ( a, b, c ) { this.a.copy( a ); this.b.copy( b ); this.c.copy( c ); return this; }, setFromPointsAndIndices: function ( points, i0, i1, i2 ) { this.a.copy( points[ i0 ] ); this.b.copy( points[ i1 ] ); this.c.copy( points[ i2 ] ); return this; }, clone: function () { return new this.constructor().copy( this ); }, copy: function ( triangle ) { this.a.copy( triangle.a ); this.b.copy( triangle.b ); this.c.copy( triangle.c ); return this; }, getArea: function () { _v0$1.subVectors( this.c, this.b ); _v1$3.subVectors( this.a, this.b ); return _v0$1.cross( _v1$3 ).length() * 0.5; }, getMidpoint: function ( target ) { if ( target === undefined ) { console.warn( 'THREE.Triangle: .getMidpoint() target is now required' ); target = new Vector3(); } return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 ); }, getNormal: function ( target ) { return Triangle.getNormal( this.a, this.b, this.c, target ); }, getPlane: function ( target ) { if ( target === undefined ) { console.warn( 'THREE.Triangle: .getPlane() target is now required' ); target = new Plane(); } return target.setFromCoplanarPoints( this.a, this.b, this.c ); }, getBarycoord: function ( point, target ) { return Triangle.getBarycoord( point, this.a, this.b, this.c, target ); }, getUV: function ( point, uv1, uv2, uv3, target ) { return Triangle.getUV( point, this.a, this.b, this.c, uv1, uv2, uv3, target ); }, containsPoint: function ( point ) { return Triangle.containsPoint( point, this.a, this.b, this.c ); }, isFrontFacing: function ( direction ) { return Triangle.isFrontFacing( this.a, this.b, this.c, direction ); }, intersectsBox: function ( box ) { return box.intersectsTriangle( this ); }, closestPointToPoint: function ( p, target ) { if ( target === undefined ) { console.warn( 'THREE.Triangle: .closestPointToPoint() target is now required' ); target = new Vector3(); } var a = this.a, b = this.b, c = this.c; var v, w; // algorithm thanks to Real-Time Collision Detection by Christer Ericson, // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc., // under the accompanying license; see chapter 5.1.5 for detailed explanation. // basically, we're distinguishing which of the voronoi regions of the triangle // the point lies in with the minimum amount of redundant computation. _vab.subVectors( b, a ); _vac.subVectors( c, a ); _vap.subVectors( p, a ); var d1 = _vab.dot( _vap ); var d2 = _vac.dot( _vap ); if ( d1 <= 0 && d2 <= 0 ) { // vertex region of A; barycentric coords (1, 0, 0) return target.copy( a ); } _vbp.subVectors( p, b ); var d3 = _vab.dot( _vbp ); var d4 = _vac.dot( _vbp ); if ( d3 >= 0 && d4 <= d3 ) { // vertex region of B; barycentric coords (0, 1, 0) return target.copy( b ); } var vc = d1 * d4 - d3 * d2; if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) { v = d1 / ( d1 - d3 ); // edge region of AB; barycentric coords (1-v, v, 0) return target.copy( a ).addScaledVector( _vab, v ); } _vcp.subVectors( p, c ); var d5 = _vab.dot( _vcp ); var d6 = _vac.dot( _vcp ); if ( d6 >= 0 && d5 <= d6 ) { // vertex region of C; barycentric coords (0, 0, 1) return target.copy( c ); } var vb = d5 * d2 - d1 * d6; if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) { w = d2 / ( d2 - d6 ); // edge region of AC; barycentric coords (1-w, 0, w) return target.copy( a ).addScaledVector( _vac, w ); } var va = d3 * d6 - d5 * d4; if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) { _vbc.subVectors( c, b ); w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) ); // edge region of BC; barycentric coords (0, 1-w, w) return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC } // face region var denom = 1 / ( va + vb + vc ); // u = va * denom v = vb * denom; w = vc * denom; return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w ); }, equals: function ( triangle ) { return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c ); } } ); /** * @author mrdoob / http://mrdoob.com/ */ var _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF, 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2, 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50, 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B, 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B, 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F, 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3, 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222, 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700, 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4, 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00, 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3, 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA, 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32, 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3, 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC, 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD, 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6, 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9, 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F, 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE, 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA, 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0, 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 }; var _hslA = { h: 0, s: 0, l: 0 }; var _hslB = { h: 0, s: 0, l: 0 }; function Color( r, g, b ) { if ( g === undefined && b === undefined ) { // r is THREE.Color, hex or string return this.set( r ); } return this.setRGB( r, g, b ); } function hue2rgb( p, q, t ) { if ( t < 0 ) { t += 1; } if ( t > 1 ) { t -= 1; } if ( t < 1 / 6 ) { return p + ( q - p ) * 6 * t; } if ( t < 1 / 2 ) { return q; } if ( t < 2 / 3 ) { return p + ( q - p ) * 6 * ( 2 / 3 - t ); } return p; } function SRGBToLinear( c ) { return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 ); } function LinearToSRGB( c ) { return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055; } Object.assign( Color.prototype, { isColor: true, r: 1, g: 1, b: 1, set: function ( value ) { if ( value && value.isColor ) { this.copy( value ); } else if ( typeof value === 'number' ) { this.setHex( value ); } else if ( typeof value === 'string' ) { this.setStyle( value ); } return this; }, setScalar: function ( scalar ) { this.r = scalar; this.g = scalar; this.b = scalar; return this; }, setHex: function ( hex ) { hex = Math.floor( hex ); this.r = ( hex >> 16 & 255 ) / 255; this.g = ( hex >> 8 & 255 ) / 255; this.b = ( hex & 255 ) / 255; return this; }, setRGB: function ( r, g, b ) { this.r = r; this.g = g; this.b = b; return this; }, setHSL: function ( h, s, l ) { // h,s,l ranges are in 0.0 - 1.0 h = MathUtils.euclideanModulo( h, 1 ); s = MathUtils.clamp( s, 0, 1 ); l = MathUtils.clamp( l, 0, 1 ); if ( s === 0 ) { this.r = this.g = this.b = l; } else { var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s ); var q = ( 2 * l ) - p; this.r = hue2rgb( q, p, h + 1 / 3 ); this.g = hue2rgb( q, p, h ); this.b = hue2rgb( q, p, h - 1 / 3 ); } return this; }, setStyle: function ( style ) { function handleAlpha( string ) { if ( string === undefined ) { return; } if ( parseFloat( string ) < 1 ) { console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' ); } } var m; if ( m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec( style ) ) { // rgb / hsl var color; var name = m[ 1 ]; var components = m[ 2 ]; switch ( name ) { case 'rgb': case 'rgba': if ( color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) { // rgb(255,0,0) rgba(255,0,0,0.5) this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255; this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255; this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255; handleAlpha( color[ 5 ] ); return this; } if ( color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) { // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5) this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100; this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100; this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100; handleAlpha( color[ 5 ] ); return this; } break; case 'hsl': case 'hsla': if ( color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) { // hsl(120,50%,50%) hsla(120,50%,50%,0.5) var h = parseFloat( color[ 1 ] ) / 360; var s = parseInt( color[ 2 ], 10 ) / 100; var l = parseInt( color[ 3 ], 10 ) / 100; handleAlpha( color[ 5 ] ); return this.setHSL( h, s, l ); } break; } } else if ( m = /^\#([A-Fa-f0-9]+)$/.exec( style ) ) { // hex color var hex = m[ 1 ]; var size = hex.length; if ( size === 3 ) { // #ff0 this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255; this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255; this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255; return this; } else if ( size === 6 ) { // #ff0000 this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255; this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255; this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255; return this; } } if ( style && style.length > 0 ) { return this.setColorName( style ); } return this; }, setColorName: function ( style ) { // color keywords var hex = _colorKeywords[ style ]; if ( hex !== undefined ) { // red this.setHex( hex ); } else { // unknown color console.warn( 'THREE.Color: Unknown color ' + style ); } return this; }, clone: function () { return new this.constructor( this.r, this.g, this.b ); }, copy: function ( color ) { this.r = color.r; this.g = color.g; this.b = color.b; return this; }, copyGammaToLinear: function ( color, gammaFactor ) { if ( gammaFactor === undefined ) { gammaFactor = 2.0; } this.r = Math.pow( color.r, gammaFactor ); this.g = Math.pow( color.g, gammaFactor ); this.b = Math.pow( color.b, gammaFactor ); return this; }, copyLinearToGamma: function ( color, gammaFactor ) { if ( gammaFactor === undefined ) { gammaFactor = 2.0; } var safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0; this.r = Math.pow( color.r, safeInverse ); this.g = Math.pow( color.g, safeInverse ); this.b = Math.pow( color.b, safeInverse ); return this; }, convertGammaToLinear: function ( gammaFactor ) { this.copyGammaToLinear( this, gammaFactor ); return this; }, convertLinearToGamma: function ( gammaFactor ) { this.copyLinearToGamma( this, gammaFactor ); return this; }, copySRGBToLinear: function ( color ) { this.r = SRGBToLinear( color.r ); this.g = SRGBToLinear( color.g ); this.b = SRGBToLinear( color.b ); return this; }, copyLinearToSRGB: function ( color ) { this.r = LinearToSRGB( color.r ); this.g = LinearToSRGB( color.g ); this.b = LinearToSRGB( color.b ); return this; }, convertSRGBToLinear: function () { this.copySRGBToLinear( this ); return this; }, convertLinearToSRGB: function () { this.copyLinearToSRGB( this ); return this; }, getHex: function () { return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0; }, getHexString: function () { return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 ); }, getHSL: function ( target ) { // h,s,l ranges are in 0.0 - 1.0 if ( target === undefined ) { console.warn( 'THREE.Color: .getHSL() target is now required' ); target = { h: 0, s: 0, l: 0 }; } var r = this.r, g = this.g, b = this.b; var max = Math.max( r, g, b ); var min = Math.min( r, g, b ); var hue, saturation; var lightness = ( min + max ) / 2.0; if ( min === max ) { hue = 0; saturation = 0; } else { var delta = max - min; saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min ); switch ( max ) { case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break; case g: hue = ( b - r ) / delta + 2; break; case b: hue = ( r - g ) / delta + 4; break; } hue /= 6; } target.h = hue; target.s = saturation; target.l = lightness; return target; }, getStyle: function () { return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')'; }, offsetHSL: function ( h, s, l ) { this.getHSL( _hslA ); _hslA.h += h; _hslA.s += s; _hslA.l += l; this.setHSL( _hslA.h, _hslA.s, _hslA.l ); return this; }, add: function ( color ) { this.r += color.r; this.g += color.g; this.b += color.b; return this; }, addColors: function ( color1, color2 ) { this.r = color1.r + color2.r; this.g = color1.g + color2.g; this.b = color1.b + color2.b; return this; }, addScalar: function ( s ) { this.r += s; this.g += s; this.b += s; return this; }, sub: function ( color ) { this.r = Math.max( 0, this.r - color.r ); this.g = Math.max( 0, this.g - color.g ); this.b = Math.max( 0, this.b - color.b ); return this; }, multiply: function ( color ) { this.r *= color.r; this.g *= color.g; this.b *= color.b; return this; }, multiplyScalar: function ( s ) { this.r *= s; this.g *= s; this.b *= s; return this; }, lerp: function ( color, alpha ) { this.r += ( color.r - this.r ) * alpha; this.g += ( color.g - this.g ) * alpha; this.b += ( color.b - this.b ) * alpha; return this; }, lerpHSL: function ( color, alpha ) { this.getHSL( _hslA ); color.getHSL( _hslB ); var h = MathUtils.lerp( _hslA.h, _hslB.h, alpha ); var s = MathUtils.lerp( _hslA.s, _hslB.s, alpha ); var l = MathUtils.lerp( _hslA.l, _hslB.l, alpha ); this.setHSL( h, s, l ); return this; }, equals: function ( c ) { return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b ); }, fromArray: function ( array, offset ) { if ( offset === undefined ) { offset = 0; } this.r = array[ offset ]; this.g = array[ offset + 1 ]; this.b = array[ offset + 2 ]; return this; }, toArray: function ( array, offset ) { if ( array === undefined ) { array = []; } if ( offset === undefined ) { offset = 0; } array[ offset ] = this.r; array[ offset + 1 ] = this.g; array[ offset + 2 ] = this.b; return array; }, toJSON: function () { return this.getHex(); } } ); Color.NAMES = _colorKeywords; /** * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ */ function Face3( a, b, c, normal, color, materialIndex ) { this.a = a; this.b = b; this.c = c; this.normal = ( normal && normal.isVector3 ) ? normal : new Vector3(); this.vertexNormals = Array.isArray( normal ) ? normal : []; this.color = ( color && color.isColor ) ? color : new Color(); this.vertexColors = Array.isArray( color ) ? color : []; this.materialIndex = materialIndex !== undefined ? materialIndex : 0; } Object.assign( Face3.prototype, { clone: function () { return new this.constructor().copy( this ); }, copy: function ( source ) { this.a = source.a; this.b = source.b; this.c = source.c; this.normal.copy( source.normal ); this.color.copy( source.color ); this.materialIndex = source.materialIndex; for ( var i = 0, il = source.vertexNormals.length; i < il; i ++ ) { this.vertexNormals[ i ] = source.vertexNormals[ i ].clone(); } for ( var i = 0, il = source.vertexColors.length; i < il; i ++ ) { this.vertexColors[ i ] = source.vertexColors[ i ].clone(); } return this; } } ); /** * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ */ var materialId = 0; function Material() { Object.defineProperty( this, 'id', { value: materialId ++ } ); this.uuid = MathUtils.generateUUID(); this.name = ''; this.type = 'Material'; this.fog = true; this.blending = NormalBlending; this.side = FrontSide; this.flatShading = false; this.vertexTangents = false; this.vertexColors = NoColors; // THREE.NoColors, THREE.VertexColors, THREE.FaceColors this.opacity = 1; this.transparent = false; this.blendSrc = SrcAlphaFactor; this.blendDst = OneMinusSrcAlphaFactor; this.blendEquation = AddEquation; this.blendSrcAlpha = null; this.blendDstAlpha = null; this.blendEquationAlpha = null; this.depthFunc = LessEqualDepth; this.depthTest = true; this.depthWrite = true; this.stencilWriteMask = 0xff; this.stencilFunc = AlwaysStencilFunc; this.stencilRef = 0; this.stencilFuncMask = 0xff; this.stencilFail = KeepStencilOp; this.stencilZFail = KeepStencilOp; this.stencilZPass = KeepStencilOp; this.stencilWrite = false; this.clippingPlanes = null; this.clipIntersection = false; this.clipShadows = false; this.shadowSide = null; this.colorWrite = true; this.precision = null; // override the renderer's default precision for this material this.polygonOffset = false; this.polygonOffsetFactor = 0; this.polygonOffsetUnits = 0; this.dithering = false; this.alphaTest = 0; this.premultipliedAlpha = false; this.visible = true; this.toneMapped = true; this.userData = {}; this.version = 0; } Material.prototype = Object.assign( Object.create( EventDispatcher.prototype ), { constructor: Material, isMaterial: true, onBeforeCompile: function () {}, setValues: function ( values ) { if ( values === undefined ) { return; } for ( var key in values ) { var newValue = values[ key ]; if ( newValue === undefined ) { console.warn( "THREE.Material: '" + key + "' parameter is undefined." ); continue; } // for backward compatability if shading is set in the constructor if ( key === 'shading' ) { console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' ); this.flatShading = ( newValue === FlatShading ) ? true : false; continue; } var currentValue = this[ key ]; if ( currentValue === undefined ) { console.warn( "THREE." + this.type + ": '" + key + "' is not a property of this material." ); continue; } if ( currentValue && currentValue.isColor ) { currentValue.set( newValue ); } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) { currentValue.copy( newValue ); } else { this[ key ] = newValue; } } }, toJSON: function ( meta ) { var isRoot = ( meta === undefined || typeof meta === 'string' ); if ( isRoot ) { meta = { textures: {}, images: {} }; } var data = { metadata: { version: 4.5, type: 'Material', generator: 'Material.toJSON' } }; // standard Material serialization data.uuid = this.uuid; data.type = this.type; if ( this.name !== '' ) { data.name = this.name; } if ( this.color && this.color.isColor ) { data.color = this.color.getHex(); } if ( this.roughness !== undefined ) { data.roughness = this.roughness; } if ( this.metalness !== undefined ) { data.metalness = this.metalness; } if ( this.sheen && this.sheen.isColor ) { data.sheen = this.sheen.getHex(); } if ( this.emissive && this.emissive.isColor ) { data.emissive = this.emissive.getHex(); } if ( this.emissiveIntensity && this.emissiveIntensity !== 1 ) { data.emissiveIntensity = this.emissiveIntensity; } if ( this.specular && this.specular.isColor ) { data.specular = this.specular.getHex(); } if ( this.shininess !== undefined ) { data.shininess = this.shininess; } if ( this.clearcoat !== undefined ) { data.clearcoat = this.clearcoat; } if ( this.clearcoatRoughness !== undefined ) { data.clearcoatRoughness = this.clearcoatRoughness; } if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) { data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid; data.clearcoatNormalScale = this.clearcoatNormalScale.toArray(); } if ( this.map && this.map.isTexture ) { data.map = this.map.toJSON( meta ).uuid; } if ( this.matcap && this.matcap.isTexture ) { data.matcap = this.matcap.toJSON( meta ).uuid; } if ( this.alphaMap && this.alphaMap.isTexture ) { data.alphaMap = this.alphaMap.toJSON( meta ).uuid; } if ( this.lightMap && this.lightMap.isTexture ) { data.lightMap = this.lightMap.toJSON( meta ).uuid; } if ( this.aoMap && this.aoMap.isTexture ) { data.aoMap = this.aoMap.toJSON( meta ).uuid; data.aoMapIntensity = this.aoMapIntensity; } if ( this.bumpMap && this.bumpMap.isTexture ) { data.bumpMap = this.bumpMap.toJSON( meta ).uuid; data.bumpScale = this.bumpScale; } if ( this.normalMap && this.normalMap.isTexture ) { data.normalMap = this.normalMap.toJSON( meta ).uuid; data.normalMapType = this.normalMapType; data.normalScale = this.normalScale.toArray(); } if ( this.displacementMap && this.displacementMap.isTexture ) { data.displacementMap = this.displacementMap.toJSON( meta ).uuid; data.displacementScale = this.displacementScale; data.displacementBias = this.displacementBias; } if ( this.roughnessMap && this.roughnessMap.isTexture ) { data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid; } if ( this.metalnessMap && this.metalnessMap.isTexture ) { data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid; } if ( this.emissiveMap && this.emissiveMap.isTexture ) { data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid; } if ( this.specularMap && this.specularMap.isTexture ) { data.specularMap = this.specularMap.toJSON( meta ).uuid; } if ( this.envMap && this.envMap.isTexture ) { data.envMap = this.envMap.toJSON( meta ).uuid; data.reflectivity = this.reflectivity; // Scale behind envMap data.refractionRatio = this.refractionRatio; if ( this.combine !== undefined ) { data.combine = this.combine; } if ( this.envMapIntensity !== undefined ) { data.envMapIntensity = this.envMapIntensity; } } if ( this.gradientMap && this.gradientMap.isTexture ) { data.gradientMap = this.gradientMap.toJSON( meta ).uuid; } if ( this.size !== undefined ) { data.size = this.size; } if ( this.sizeAttenuation !== undefined ) { data.sizeAttenuation = this.sizeAttenuation; } if ( this.blending !== NormalBlending ) { data.blending = this.blending; } if ( this.flatShading === true ) { data.flatShading = this.flatShading; } if ( this.side !== FrontSide ) { data.side = this.side; } if ( this.vertexColors !== NoColors ) { data.vertexColors = this.vertexColors; } if ( this.opacity < 1 ) { data.opacity = this.opacity; } if ( this.transparent === true ) { data.transparent = this.transparent; } data.depthFunc = this.depthFunc; data.depthTest = this.depthTest; data.depthWrite = this.depthWrite; data.stencilWrite = this.stencilWrite; data.stencilWriteMask = this.stencilWriteMask; data.stencilFunc = this.stencilFunc; data.stencilRef = this.stencilRef; data.stencilFuncMask = this.stencilFuncMask; data.stencilFail = this.stencilFail; data.stencilZFail = this.stencilZFail; data.stencilZPass = this.stencilZPass; // rotation (SpriteMaterial) if ( this.rotation && this.rotation !== 0 ) { data.rotation = this.rotation; } if ( this.polygonOffset === true ) { data.polygonOffset = true; } if ( this.polygonOffsetFactor !== 0 ) { data.polygonOffsetFactor = this.polygonOffsetFactor; } if ( this.polygonOffsetUnits !== 0 ) { data.polygonOffsetUnits = this.polygonOffsetUnits; } if ( this.linewidth && this.linewidth !== 1 ) { data.linewidth = this.linewidth; } if ( this.dashSize !== undefined ) { data.dashSize = this.dashSize; } if ( this.gapSize !== undefined ) { data.gapSize = this.gapSize; } if ( this.scale !== undefined ) { data.scale = this.scale; } if ( this.dithering === true ) { data.dithering = true; } if ( this.alphaTest > 0 ) { data.alphaTest = this.alphaTest; } if ( this.premultipliedAlpha === true ) { data.premultipliedAlpha = this.premultipliedAlpha; } if ( this.wireframe === true ) { data.wireframe = this.wireframe; } if ( this.wireframeLinewidth > 1 ) { data.wireframeLinewidth = this.wireframeLinewidth; } if ( this.wireframeLinecap !== 'round' ) { data.wireframeLinecap = this.wireframeLinecap; } if ( this.wireframeLinejoin !== 'round' ) { data.wireframeLinejoin = this.wireframeLinejoin; } if ( this.morphTargets === true ) { data.morphTargets = true; } if ( this.morphNormals === true ) { data.morphNormals = true; } if ( this.skinning === true ) { data.skinning = true; } if ( this.visible === false ) { data.visible = false; } if ( this.toneMapped === false ) { data.toneMapped = false; } if ( JSON.stringify( this.userData ) !== '{}' ) { data.userData = this.userData; } // TODO: Copied from Object3D.toJSON function extractFromCache( cache ) { var values = []; for ( var key in cache ) { var data = cache[ key ]; delete data.metadata; values.push( data ); } return values; } if ( isRoot ) { var textures = extractFromCache( meta.textures ); var images = extractFromCache( meta.images ); if ( textures.length > 0 ) { data.textures = textures; } if ( images.length > 0 ) { data.images = images; } } return data; }, clone: function () { return new this.constructor().copy( this ); }, copy: function ( source ) { this.name = source.name; this.fog = source.fog; this.blending = source.blending; this.side = source.side; this.flatShading = source.flatShading; this.vertexTangents = source.vertexTangents; this.vertexColors = source.vertexColors; this.opacity = source.opacity; this.transparent = source.transparent; this.blendSrc = source.blendSrc; this.blendDst = source.blendDst; this.blendEquation = source.blendEquation; this.blendSrcAlpha = source.blendSrcAlpha; this.blendDstAlpha = source.blendDstAlpha; this.blendEquationAlpha = source.blendEquationAlpha; this.depthFunc = source.depthFunc; this.depthTest = source.depthTest; this.depthWrite = source.depthWrite; this.stencilWriteMask = source.stencilWriteMask; this.stencilFunc = source.stencilFunc; this.stencilRef = source.stencilRef; this.stencilFuncMask = source.stencilFuncMask; this.stencilFail = source.stencilFail; this.stencilZFail = source.stencilZFail; this.stencilZPass = source.stencilZPass; this.stencilWrite = source.stencilWrite; var srcPlanes = source.clippingPlanes, dstPlanes = null; if ( srcPlanes !== null ) { var n = srcPlanes.length; dstPlanes = new Array( n ); for ( var i = 0; i !== n; ++ i ) { dstPlanes[ i ] = srcPlanes[ i ].clone(); } } this.clippingPlanes = dstPlanes; this.clipIntersection = source.clipIntersection; this.clipShadows = source.clipShadows; this.shadowSide = source.shadowSide; this.colorWrite = source.colorWrite; this.precision = source.precision; this.polygonOffset = source.polygonOffset; this.polygonOffsetFactor = source.polygonOffsetFactor; this.polygonOffsetUnits = source.polygonOffsetUnits; this.dithering = source.dithering; this.alphaTest = source.alphaTest; this.premultipliedAlpha = source.premultipliedAlpha; this.visible = source.visible; this.toneMapped = source.toneMapped; this.userData = JSON.parse( JSON.stringify( source.userData ) ); return this; }, dispose: function () { this.dispatchEvent( { type: 'dispose' } ); } } ); Object.defineProperty( Material.prototype, 'needsUpdate', { set: function ( value ) { if ( value === true ) { this.version ++; } } } ); /** * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ * * parameters = { * color: , * opacity: , * map: new THREE.Texture( ), * * lightMap: new THREE.Texture( ), * lightMapIntensity: * * aoMap: new THREE.Texture( ), * aoMapIntensity: * * specularMap: new THREE.Texture( ), * * alphaMap: new THREE.Texture( ), * * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ), * combine: THREE.Multiply, * reflectivity: , * refractionRatio: , * * depthTest: , * depthWrite: , * * wireframe: , * wireframeLinewidth: , * * skinning: , * morphTargets: * } */ function MeshBasicMaterial( parameters ) { Material.call( this ); this.type = 'MeshBasicMaterial'; this.color = new Color( 0xffffff ); // emissive this.map = null; this.lightMap = null; this.lightMapIntensity = 1.0; this.aoMap = null; this.aoMapIntensity = 1.0; this.specularMap = null; this.alphaMap = null; this.envMap = null; this.combine = MultiplyOperation; this.reflectivity = 1; this.refractionRatio = 0.98; this.wireframe = false; this.wireframeLinewidth = 1; this.wireframeLinecap = 'round'; this.wireframeLinejoin = 'round'; this.skinning = false; this.morphTargets = false; this.setValues( parameters ); } MeshBasicMaterial.prototype = Object.create( Material.prototype ); MeshBasicMaterial.prototype.constructor = MeshBasicMaterial; MeshBasicMaterial.prototype.isMeshBasicMaterial = true; MeshBasicMaterial.prototype.copy = function ( source ) { Material.prototype.copy.call( this, source ); this.color.copy( source.color ); this.map = source.map; this.lightMap = source.lightMap; this.lightMapIntensity = source.lightMapIntensity; this.aoMap = source.aoMap; this.aoMapIntensity = source.aoMapIntensity; this.specularMap = source.specularMap; this.alphaMap = source.alphaMap; this.envMap = source.envMap; this.combine = source.combine; this.reflectivity = source.reflectivity; this.refractionRatio = source.refractionRatio; this.wireframe = source.wireframe; this.wireframeLinewidth = source.wireframeLinewidth; this.wireframeLinecap = source.wireframeLinecap; this.wireframeLinejoin = source.wireframeLinejoin; this.skinning = source.skinning; this.morphTargets = source.morphTargets; return this; }; /** * @author mrdoob / http://mrdoob.com/ */ var _vector$3 = new Vector3(); function BufferAttribute( array, itemSize, normalized ) { if ( Array.isArray( array ) ) { throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' ); } this.name = ''; this.array = array; this.itemSize = itemSize; this.count = array !== undefined ? array.length / itemSize : 0; this.normalized = normalized === true; this.usage = StaticDrawUsage; this.updateRange = { offset: 0, count: - 1 }; this.version = 0; } Object.defineProperty( BufferAttribute.prototype, 'needsUpdate', { set: function ( value ) { if ( value === true ) { this.version ++; } } } ); Object.assign( BufferAttribute.prototype, { isBufferAttribute: true, onUploadCallback: function () {}, setUsage: function ( value ) { this.usage = value; return this; }, copy: function ( source ) { this.name = source.name; this.array = new source.array.constructor( source.array ); this.itemSize = source.itemSize; this.count = source.count; this.normalized = source.normalized; this.usage = source.usage; return this; }, copyAt: function ( index1, attribute, index2 ) { index1 *= this.itemSize; index2 *= attribute.itemSize; for ( var i = 0, l = this.itemSize; i < l; i ++ ) { this.array[ index1 + i ] = attribute.array[ index2 + i ]; } return this; }, copyArray: function ( array ) { this.array.set( array ); return this; }, copyColorsArray: function ( colors ) { var array = this.array, offset = 0; for ( var i = 0, l = colors.length; i < l; i ++ ) { var color = colors[ i ]; if ( color === undefined ) { console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i ); color = new Color(); } array[ offset ++ ] = color.r; array[ offset ++ ] = color.g; array[ offset ++ ] = color.b; } return this; }, copyVector2sArray: function ( vectors ) { var array = this.array, offset = 0; for ( var i = 0, l = vectors.length; i < l; i ++ ) { var vector = vectors[ i ]; if ( vector === undefined ) { console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i ); vector = new Vector2(); } array[ offset ++ ] = vector.x; array[ offset ++ ] = vector.y; } return this; }, copyVector3sArray: function ( vectors ) { var array = this.array, offset = 0; for ( var i = 0, l = vectors.length; i < l; i ++ ) { var vector = vectors[ i ]; if ( vector === undefined ) { console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i ); vector = new Vector3(); } array[ offset ++ ] = vector.x; array[ offset ++ ] = vector.y; array[ offset ++ ] = vector.z; } return this; }, copyVector4sArray: function ( vectors ) { var array = this.array, offset = 0; for ( var i = 0, l = vectors.length; i < l; i ++ ) { var vector = vectors[ i ]; if ( vector === undefined ) { console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i ); vector = new Vector4(); } array[ offset ++ ] = vector.x; array[ offset ++ ] = vector.y; array[ offset ++ ] = vector.z; array[ offset ++ ] = vector.w; } return this; }, applyMatrix3: function ( m ) { for ( var i = 0, l = this.count; i < l; i ++ ) { _vector$3.x = this.getX( i ); _vector$3.y = this.getY( i ); _vector$3.z = this.getZ( i ); _vector$3.applyMatrix3( m ); this.setXYZ( i, _vector$3.x, _vector$3.y, _vector$3.z ); } return this; }, applyMatrix4: function ( m ) { for ( var i = 0, l = this.count; i < l; i ++ ) { _vector$3.x = this.getX( i ); _vector$3.y = this.getY( i ); _vector$3.z = this.getZ( i ); _vector$3.applyMatrix4( m ); this.setXYZ( i, _vector$3.x, _vector$3.y, _vector$3.z ); } return this; }, applyNormalMatrix: function ( m ) { for ( var i = 0, l = this.count; i < l; i ++ ) { _vector$3.x = this.getX( i ); _vector$3.y = this.getY( i ); _vector$3.z = this.getZ( i ); _vector$3.applyNormalMatrix( m ); this.setXYZ( i, _vector$3.x, _vector$3.y, _vector$3.z ); } return this; }, transformDirection: function ( m ) { for ( var i = 0, l = this.count; i < l; i ++ ) { _vector$3.x = this.getX( i ); _vector$3.y = this.getY( i ); _vector$3.z = this.getZ( i ); _vector$3.transformDirection( m ); this.setXYZ( i, _vector$3.x, _vector$3.y, _vector$3.z ); } return this; }, set: function ( value, offset ) { if ( offset === undefined ) { offset = 0; } this.array.set( value, offset ); return this; }, getX: function ( index ) { return this.array[ index * this.itemSize ]; }, setX: function ( index, x ) { this.array[ index * this.itemSize ] = x; return this; }, getY: function ( index ) { return this.array[ index * this.itemSize + 1 ]; }, setY: function ( index, y ) { this.array[ index * this.itemSize + 1 ] = y; return this; }, getZ: function ( index ) { return this.array[ index * this.itemSize + 2 ]; }, setZ: function ( index, z ) { this.array[ index * this.itemSize + 2 ] = z; return this; }, getW: function ( index ) { return this.array[ index * this.itemSize + 3 ]; }, setW: function ( index, w ) { this.array[ index * this.itemSize + 3 ] = w; return this; }, setXY: function ( index, x, y ) { index *= this.itemSize; this.array[ index + 0 ] = x; this.array[ index + 1 ] = y; return this; }, setXYZ: function ( index, x, y, z ) { index *= this.itemSize; this.array[ index + 0 ] = x; this.array[ index + 1 ] = y; this.array[ index + 2 ] = z; return this; }, setXYZW: function ( index, x, y, z, w ) { index *= this.itemSize; this.array[ index + 0 ] = x; this.array[ index + 1 ] = y; this.array[ index + 2 ] = z; this.array[ index + 3 ] = w; return this; }, onUpload: function ( callback ) { this.onUploadCallback = callback; return this; }, clone: function () { return new this.constructor( this.array, this.itemSize ).copy( this ); }, toJSON: function () { return { itemSize: this.itemSize, type: this.array.constructor.name, array: Array.prototype.slice.call( this.array ), normalized: this.normalized }; } } ); // function Int8BufferAttribute( array, itemSize, normalized ) { BufferAttribute.call( this, new Int8Array( array ), itemSize, normalized ); } Int8BufferAttribute.prototype = Object.create( BufferAttribute.prototype ); Int8BufferAttribute.prototype.constructor = Int8BufferAttribute; function Uint8BufferAttribute( array, itemSize, normalized ) { BufferAttribute.call( this, new Uint8Array( array ), itemSize, normalized ); } Uint8BufferAttribute.prototype = Object.create( BufferAttribute.prototype ); Uint8BufferAttribute.prototype.constructor = Uint8BufferAttribute; function Uint8ClampedBufferAttribute( array, itemSize, normalized ) { BufferAttribute.call( this, new Uint8ClampedArray( array ), itemSize, normalized ); } Uint8ClampedBufferAttribute.prototype = Object.create( BufferAttribute.prototype ); Uint8ClampedBufferAttribute.prototype.constructor = Uint8ClampedBufferAttribute; function Int16BufferAttribute( array, itemSize, normalized ) { BufferAttribute.call( this, new Int16Array( array ), itemSize, normalized ); } Int16BufferAttribute.prototype = Object.create( BufferAttribute.prototype ); Int16BufferAttribute.prototype.constructor = Int16BufferAttribute; function Uint16BufferAttribute( array, itemSize, normalized ) { BufferAttribute.call( this, new Uint16Array( array ), itemSize, normalized ); } Uint16BufferAttribute.prototype = Object.create( BufferAttribute.prototype ); Uint16BufferAttribute.prototype.constructor = Uint16BufferAttribute; function Int32BufferAttribute( array, itemSize, normalized ) { BufferAttribute.call( this, new Int32Array( array ), itemSize, normalized ); } Int32BufferAttribute.prototype = Object.create( BufferAttribute.prototype ); Int32BufferAttribute.prototype.constructor = Int32BufferAttribute; function Uint32BufferAttribute( array, itemSize, normalized ) { BufferAttribute.call( this, new Uint32Array( array ), itemSize, normalized ); } Uint32BufferAttribute.prototype = Object.create( BufferAttribute.prototype ); Uint32BufferAttribute.prototype.constructor = Uint32BufferAttribute; function Float32BufferAttribute( array, itemSize, normalized ) { BufferAttribute.call( this, new Float32Array( array ), itemSize, normalized ); } Float32BufferAttribute.prototype = Object.create( BufferAttribute.prototype ); Float32BufferAttribute.prototype.constructor = Float32BufferAttribute; function Float64BufferAttribute( array, itemSize, normalized ) { BufferAttribute.call( this, new Float64Array( array ), itemSize, normalized ); } Float64BufferAttribute.prototype = Object.create( BufferAttribute.prototype ); Float64BufferAttribute.prototype.constructor = Float64BufferAttribute; /** * @author mrdoob / http://mrdoob.com/ */ function DirectGeometry() { this.vertices = []; this.normals = []; this.colors = []; this.uvs = []; this.uvs2 = []; this.groups = []; this.morphTargets = {}; this.skinWeights = []; this.skinIndices = []; // this.lineDistances = []; this.boundingBox = null; this.boundingSphere = null; // update flags this.verticesNeedUpdate = false; this.normalsNeedUpdate = false; this.colorsNeedUpdate = false; this.uvsNeedUpdate = false; this.groupsNeedUpdate = false; } Object.assign( DirectGeometry.prototype, { computeGroups: function ( geometry ) { var group; var groups = []; var materialIndex = undefined; var faces = geometry.faces; for ( var i = 0; i < faces.length; i ++ ) { var face = faces[ i ]; // materials if ( face.materialIndex !== materialIndex ) { materialIndex = face.materialIndex; if ( group !== undefined ) { group.count = ( i * 3 ) - group.start; groups.push( group ); } group = { start: i * 3, materialIndex: materialIndex }; } } if ( group !== undefined ) { group.count = ( i * 3 ) - group.start; groups.push( group ); } this.groups = groups; }, fromGeometry: function ( geometry ) { var faces = geometry.faces; var vertices = geometry.vertices; var faceVertexUvs = geometry.faceVertexUvs; var hasFaceVertexUv = faceVertexUvs[ 0 ] && faceVertexUvs[ 0 ].length > 0; var hasFaceVertexUv2 = faceVertexUvs[ 1 ] && faceVertexUvs[ 1 ].length > 0; // morphs var morphTargets = geometry.morphTargets; var morphTargetsLength = morphTargets.length; var morphTargetsPosition; if ( morphTargetsLength > 0 ) { morphTargetsPosition = []; for ( var i = 0; i < morphTargetsLength; i ++ ) { morphTargetsPosition[ i ] = { name: morphTargets[ i ].name, data: [] }; } this.morphTargets.position = morphTargetsPosition; } var morphNormals = geometry.morphNormals; var morphNormalsLength = morphNormals.length; var morphTargetsNormal; if ( morphNormalsLength > 0 ) { morphTargetsNormal = []; for ( var i = 0; i < morphNormalsLength; i ++ ) { morphTargetsNormal[ i ] = { name: morphNormals[ i ].name, data: [] }; } this.morphTargets.normal = morphTargetsNormal; } // skins var skinIndices = geometry.skinIndices; var skinWeights = geometry.skinWeights; var hasSkinIndices = skinIndices.length === vertices.length; var hasSkinWeights = skinWeights.length === vertices.length; // if ( vertices.length > 0 && faces.length === 0 ) { console.error( 'THREE.DirectGeometry: Faceless geometries are not supported.' ); } for ( var i = 0; i < faces.length; i ++ ) { var face = faces[ i ]; this.vertices.push( vertices[ face.a ], vertices[ face.b ], vertices[ face.c ] ); var vertexNormals = face.vertexNormals; if ( vertexNormals.length === 3 ) { this.normals.push( vertexNormals[ 0 ], vertexNormals[ 1 ], vertexNormals[ 2 ] ); } else { var normal = face.normal; this.normals.push( normal, normal, normal ); } var vertexColors = face.vertexColors; if ( vertexColors.length === 3 ) { this.colors.push( vertexColors[ 0 ], vertexColors[ 1 ], vertexColors[ 2 ] ); } else { var color = face.color; this.colors.push( color, color, color ); } if ( hasFaceVertexUv === true ) { var vertexUvs = faceVertexUvs[ 0 ][ i ]; if ( vertexUvs !== undefined ) { this.uvs.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] ); } else { console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i ); this.uvs.push( new Vector2(), new Vector2(), new Vector2() ); } } if ( hasFaceVertexUv2 === true ) { var vertexUvs = faceVertexUvs[ 1 ][ i ]; if ( vertexUvs !== undefined ) { this.uvs2.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] ); } else { console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i ); this.uvs2.push( new Vector2(), new Vector2(), new Vector2() ); } } // morphs for ( var j = 0; j < morphTargetsLength; j ++ ) { var morphTarget = morphTargets[ j ].vertices; morphTargetsPosition[ j ].data.push( morphTarget[ face.a ], morphTarget[ face.b ], morphTarget[ face.c ] ); } for ( var j = 0; j < morphNormalsLength; j ++ ) { var morphNormal = morphNormals[ j ].vertexNormals[ i ]; morphTargetsNormal[ j ].data.push( morphNormal.a, morphNormal.b, morphNormal.c ); } // skins if ( hasSkinIndices ) { this.skinIndices.push( skinIndices[ face.a ], skinIndices[ face.b ], skinIndices[ face.c ] ); } if ( hasSkinWeights ) { this.skinWeights.push( skinWeights[ face.a ], skinWeights[ face.b ], skinWeights[ face.c ] ); } } this.computeGroups( geometry ); this.verticesNeedUpdate = geometry.verticesNeedUpdate; this.normalsNeedUpdate = geometry.normalsNeedUpdate; this.colorsNeedUpdate = geometry.colorsNeedUpdate; this.uvsNeedUpdate = geometry.uvsNeedUpdate; this.groupsNeedUpdate = geometry.groupsNeedUpdate; if ( geometry.boundingSphere !== null ) { this.boundingSphere = geometry.boundingSphere.clone(); } if ( geometry.boundingBox !== null ) { this.boundingBox = geometry.boundingBox.clone(); } return this; } } ); /** * @author mrdoob / http://mrdoob.com/ */ function arrayMax( array ) { if ( array.length === 0 ) { return - Infinity; } var max = array[ 0 ]; for ( var i = 1, l = array.length; i < l; ++ i ) { if ( array[ i ] > max ) { max = array[ i ]; } } return max; } /** * @author alteredq / http://alteredqualia.com/ * @author mrdoob / http://mrdoob.com/ */ var _bufferGeometryId = 1; // BufferGeometry uses odd numbers as Id var _m1$2 = new Matrix4(); var _obj = new Object3D(); var _offset = new Vector3(); var _box$2 = new Box3(); var _boxMorphTargets = new Box3(); var _vector$4 = new Vector3(); function BufferGeometry() { Object.defineProperty( this, 'id', { value: _bufferGeometryId += 2 } ); this.uuid = MathUtils.generateUUID(); this.name = ''; this.type = 'BufferGeometry'; this.index = null; this.attributes = {}; this.morphAttributes = {}; this.morphTargetsRelative = false; this.groups = []; this.boundingBox = null; this.boundingSphere = null; this.drawRange = { start: 0, count: Infinity }; this.userData = {}; } BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototype ), { constructor: BufferGeometry, isBufferGeometry: true, getIndex: function () { return this.index; }, setIndex: function ( index ) { if ( Array.isArray( index ) ) { this.index = new ( arrayMax( index ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 ); } else { this.index = index; } }, getAttribute: function ( name ) { return this.attributes[ name ]; }, setAttribute: function ( name, attribute ) { this.attributes[ name ] = attribute; return this; }, deleteAttribute: function ( name ) { delete this.attributes[ name ]; return this; }, addGroup: function ( start, count, materialIndex ) { this.groups.push( { start: start, count: count, materialIndex: materialIndex !== undefined ? materialIndex : 0 } ); }, clearGroups: function () { this.groups = []; }, setDrawRange: function ( start, count ) { this.drawRange.start = start; this.drawRange.count = count; }, applyMatrix4: function ( matrix ) { var position = this.attributes.position; if ( position !== undefined ) { position.applyMatrix4( matrix ); position.needsUpdate = true; } var normal = this.attributes.normal; if ( normal !== undefined ) { var normalMatrix = new Matrix3().getNormalMatrix( matrix ); normal.applyNormalMatrix( normalMatrix ); normal.needsUpdate = true; } var tangent = this.attributes.tangent; if ( tangent !== undefined ) { tangent.transformDirection( matrix ); tangent.needsUpdate = true; } if ( this.boundingBox !== null ) { this.computeBoundingBox(); } if ( this.boundingSphere !== null ) { this.computeBoundingSphere(); } return this; }, rotateX: function ( angle ) { // rotate geometry around world x-axis _m1$2.makeRotationX( angle ); this.applyMatrix4( _m1$2 ); return this; }, rotateY: function ( angle ) { // rotate geometry around world y-axis _m1$2.makeRotationY( angle ); this.applyMatrix4( _m1$2 ); return this; }, rotateZ: function ( angle ) { // rotate geometry around world z-axis _m1$2.makeRotationZ( angle ); this.applyMatrix4( _m1$2 ); return this; }, translate: function ( x, y, z ) { // translate geometry _m1$2.makeTranslation( x, y, z ); this.applyMatrix4( _m1$2 ); return this; }, scale: function ( x, y, z ) { // scale geometry _m1$2.makeScale( x, y, z ); this.applyMatrix4( _m1$2 ); return this; }, lookAt: function ( vector ) { _obj.lookAt( vector ); _obj.updateMatrix(); this.applyMatrix4( _obj.matrix ); return this; }, center: function () { this.computeBoundingBox(); this.boundingBox.getCenter( _offset ).negate(); this.translate( _offset.x, _offset.y, _offset.z ); return this; }, setFromObject: function ( object ) { // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this ); var geometry = object.geometry; if ( object.isPoints || object.isLine ) { var positions = new Float32BufferAttribute( geometry.vertices.length * 3, 3 ); var colors = new Float32BufferAttribute( geometry.colors.length * 3, 3 ); this.setAttribute( 'position', positions.copyVector3sArray( geometry.vertices ) ); this.setAttribute( 'color', colors.copyColorsArray( geometry.colors ) ); if ( geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length ) { var lineDistances = new Float32BufferAttribute( geometry.lineDistances.length, 1 ); this.setAttribute( 'lineDistance', lineDistances.copyArray( geometry.lineDistances ) ); } if ( geometry.boundingSphere !== null ) { this.boundingSphere = geometry.boundingSphere.clone(); } if ( geometry.boundingBox !== null ) { this.boundingBox = geometry.boundingBox.clone(); } } else if ( object.isMesh ) { if ( geometry && geometry.isGeometry ) { this.fromGeometry( geometry ); } } return this; }, setFromPoints: function ( points ) { var position = []; for ( var i = 0, l = points.length; i < l; i ++ ) { var point = points[ i ]; position.push( point.x, point.y, point.z || 0 ); } this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) ); return this; }, updateFromObject: function ( object ) { var geometry = object.geometry; if ( object.isMesh ) { var direct = geometry.__directGeometry; if ( geometry.elementsNeedUpdate === true ) { direct = undefined; geometry.elementsNeedUpdate = false; } if ( direct === undefined ) { return this.fromGeometry( geometry ); } direct.verticesNeedUpdate = geometry.verticesNeedUpdate; direct.normalsNeedUpdate = geometry.normalsNeedUpdate; direct.colorsNeedUpdate = geometry.colorsNeedUpdate; direct.uvsNeedUpdate = geometry.uvsNeedUpdate; direct.groupsNeedUpdate = geometry.groupsNeedUpdate; geometry.verticesNeedUpdate = false; geometry.normalsNeedUpdate = false; geometry.colorsNeedUpdate = false; geometry.uvsNeedUpdate = false; geometry.groupsNeedUpdate = false; geometry = direct; } var attribute; if ( geometry.verticesNeedUpdate === true ) { attribute = this.attributes.position; if ( attribute !== undefined ) { attribute.copyVector3sArray( geometry.vertices ); attribute.needsUpdate = true; } geometry.verticesNeedUpdate = false; } if ( geometry.normalsNeedUpdate === true ) { attribute = this.attributes.normal; if ( attribute !== undefined ) { attribute.copyVector3sArray( geometry.normals ); attribute.needsUpdate = true; } geometry.normalsNeedUpdate = false; } if ( geometry.colorsNeedUpdate === true ) { attribute = this.attributes.color; if ( attribute !== undefined ) { attribute.copyColorsArray( geometry.colors ); attribute.needsUpdate = true; } geometry.colorsNeedUpdate = false; } if ( geometry.uvsNeedUpdate ) { attribute = this.attributes.uv; if ( attribute !== undefined ) { attribute.copyVector2sArray( geometry.uvs ); attribute.needsUpdate = true; } geometry.uvsNeedUpdate = false; } if ( geometry.lineDistancesNeedUpdate ) { attribute = this.attributes.lineDistance; if ( attribute !== undefined ) { attribute.copyArray( geometry.lineDistances ); attribute.needsUpdate = true; } geometry.lineDistancesNeedUpdate = false; } if ( geometry.groupsNeedUpdate ) { geometry.computeGroups( object.geometry ); this.groups = geometry.groups; geometry.groupsNeedUpdate = false; } return this; }, fromGeometry: function ( geometry ) { geometry.__directGeometry = new DirectGeometry().fromGeometry( geometry ); return this.fromDirectGeometry( geometry.__directGeometry ); }, fromDirectGeometry: function ( geometry ) { var positions = new Float32Array( geometry.vertices.length * 3 ); this.setAttribute( 'position', new BufferAttribute( positions, 3 ).copyVector3sArray( geometry.vertices ) ); if ( geometry.normals.length > 0 ) { var normals = new Float32Array( geometry.normals.length * 3 ); this.setAttribute( 'normal', new BufferAttribute( normals, 3 ).copyVector3sArray( geometry.normals ) ); } if ( geometry.colors.length > 0 ) { var colors = new Float32Array( geometry.colors.length * 3 ); this.setAttribute( 'color', new BufferAttribute( colors, 3 ).copyColorsArray( geometry.colors ) ); } if ( geometry.uvs.length > 0 ) { var uvs = new Float32Array( geometry.uvs.length * 2 ); this.setAttribute( 'uv', new BufferAttribute( uvs, 2 ).copyVector2sArray( geometry.uvs ) ); } if ( geometry.uvs2.length > 0 ) { var uvs2 = new Float32Array( geometry.uvs2.length * 2 ); this.setAttribute( 'uv2', new BufferAttribute( uvs2, 2 ).copyVector2sArray( geometry.uvs2 ) ); } // groups this.groups = geometry.groups; // morphs for ( var name in geometry.morphTargets ) { var array = []; var morphTargets = geometry.morphTargets[ name ]; for ( var i = 0, l = morphTargets.length; i < l; i ++ ) { var morphTarget = morphTargets[ i ]; var attribute = new Float32BufferAttribute( morphTarget.data.length * 3, 3 ); attribute.name = morphTarget.name; array.push( attribute.copyVector3sArray( morphTarget.data ) ); } this.morphAttributes[ name ] = array; } // skinning if ( geometry.skinIndices.length > 0 ) { var skinIndices = new Float32BufferAttribute( geometry.skinIndices.length * 4, 4 ); this.setAttribute( 'skinIndex', skinIndices.copyVector4sArray( geometry.skinIndices ) ); } if ( geometry.skinWeights.length > 0 ) { var skinWeights = new Float32BufferAttribute( geometry.skinWeights.length * 4, 4 ); this.setAttribute( 'skinWeight', skinWeights.copyVector4sArray( geometry.skinWeights ) ); } // if ( geometry.boundingSphere !== null ) { this.boundingSphere = geometry.boundingSphere.clone(); } if ( geometry.boundingBox !== null ) { this.boundingBox = geometry.boundingBox.clone(); } return this; }, computeBoundingBox: function () { if ( this.boundingBox === null ) { this.boundingBox = new Box3(); } var position = this.attributes.position; var morphAttributesPosition = this.morphAttributes.position; if ( position !== undefined ) { this.boundingBox.setFromBufferAttribute( position ); // process morph attributes if present if ( morphAttributesPosition ) { for ( var i = 0, il = morphAttributesPosition.length; i < il; i ++ ) { var morphAttribute = morphAttributesPosition[ i ]; _box$2.setFromBufferAttribute( morphAttribute ); if ( this.morphTargetsRelative ) { _vector$4.addVectors( this.boundingBox.min, _box$2.min ); this.boundingBox.expandByPoint( _vector$4 ); _vector$4.addVectors( this.boundingBox.max, _box$2.max ); this.boundingBox.expandByPoint( _vector$4 ); } else { this.boundingBox.expandByPoint( _box$2.min ); this.boundingBox.expandByPoint( _box$2.max ); } } } } else { this.boundingBox.makeEmpty(); } if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) { console.error( 'THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this ); } }, computeBoundingSphere: function () { if ( this.boundingSphere === null ) { this.boundingSphere = new Sphere(); } var position = this.attributes.position; var morphAttributesPosition = this.morphAttributes.position; if ( position ) { // first, find the center of the bounding sphere var center = this.boundingSphere.center; _box$2.setFromBufferAttribute( position ); // process morph attributes if present if ( morphAttributesPosition ) { for ( var i = 0, il = morphAttributesPosition.length; i < il; i ++ ) { var morphAttribute = morphAttributesPosition[ i ]; _boxMorphTargets.setFromBufferAttribute( morphAttribute ); if ( this.morphTargetsRelative ) { _vector$4.addVectors( _box$2.min, _boxMorphTargets.min ); _box$2.expandByPoint( _vector$4 ); _vector$4.addVectors( _box$2.max, _boxMorphTargets.max ); _box$2.expandByPoint( _vector$4 ); } else { _box$2.expandByPoint( _boxMorphTargets.min ); _box$2.expandByPoint( _boxMorphTargets.max ); } } } _box$2.getCenter( center ); // second, try to find a boundingSphere with a radius smaller than the // boundingSphere of the boundingBox: sqrt(3) smaller in the best case var maxRadiusSq = 0; for ( var i = 0, il = position.count; i < il; i ++ ) { _vector$4.fromBufferAttribute( position, i ); maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$4 ) ); } // process morph attributes if present if ( morphAttributesPosition ) { for ( var i = 0, il = morphAttributesPosition.length; i < il; i ++ ) { var morphAttribute = morphAttributesPosition[ i ]; var morphTargetsRelative = this.morphTargetsRelative; for ( var j = 0, jl = morphAttribute.count; j < jl; j ++ ) { _vector$4.fromBufferAttribute( morphAttribute, j ); if ( morphTargetsRelative ) { _offset.fromBufferAttribute( position, j ); _vector$4.add( _offset ); } maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$4 ) ); } } } this.boundingSphere.radius = Math.sqrt( maxRadiusSq ); if ( isNaN( this.boundingSphere.radius ) ) { console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this ); } } }, computeFaceNormals: function () { // backwards compatibility }, computeVertexNormals: function () { var index = this.index; var attributes = this.attributes; if ( attributes.position ) { var positions = attributes.position.array; if ( attributes.normal === undefined ) { this.setAttribute( 'normal', new BufferAttribute( new Float32Array( positions.length ), 3 ) ); } else { // reset existing normals to zero var array = attributes.normal.array; for ( var i = 0, il = array.length; i < il; i ++ ) { array[ i ] = 0; } } var normals = attributes.normal.array; var vA, vB, vC; var pA = new Vector3(), pB = new Vector3(), pC = new Vector3(); var cb = new Vector3(), ab = new Vector3(); // indexed elements if ( index ) { var indices = index.array; for ( var i = 0, il = index.count; i < il; i += 3 ) { vA = indices[ i + 0 ] * 3; vB = indices[ i + 1 ] * 3; vC = indices[ i + 2 ] * 3; pA.fromArray( positions, vA ); pB.fromArray( positions, vB ); pC.fromArray( positions, vC ); cb.subVectors( pC, pB ); ab.subVectors( pA, pB ); cb.cross( ab ); normals[ vA ] += cb.x; normals[ vA + 1 ] += cb.y; normals[ vA + 2 ] += cb.z; normals[ vB ] += cb.x; normals[ vB + 1 ] += cb.y; normals[ vB + 2 ] += cb.z; normals[ vC ] += cb.x; normals[ vC + 1 ] += cb.y; normals[ vC + 2 ] += cb.z; } } else { // non-indexed elements (unconnected triangle soup) for ( var i = 0, il = positions.length; i < il; i += 9 ) { pA.fromArray( positions, i ); pB.fromArray( positions, i + 3 ); pC.fromArray( positions, i + 6 ); cb.subVectors( pC, pB ); ab.subVectors( pA, pB ); cb.cross( ab ); normals[ i ] = cb.x; normals[ i + 1 ] = cb.y; normals[ i + 2 ] = cb.z; normals[ i + 3 ] = cb.x; normals[ i + 4 ] = cb.y; normals[ i + 5 ] = cb.z; normals[ i + 6 ] = cb.x; normals[ i + 7 ] = cb.y; normals[ i + 8 ] = cb.z; } } this.normalizeNormals(); attributes.normal.needsUpdate = true; } }, merge: function ( geometry, offset ) { if ( ! ( geometry && geometry.isBufferGeometry ) ) { console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry ); return; } if ( offset === undefined ) { offset = 0; console.warn( 'THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. ' + 'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.' ); } var attributes = this.attributes; for ( var key in attributes ) { if ( geometry.attributes[ key ] === undefined ) { continue; } var attribute1 = attributes[ key ]; var attributeArray1 = attribute1.array; var attribute2 = geometry.attributes[ key ]; var attributeArray2 = attribute2.array; var attributeOffset = attribute2.itemSize * offset; var length = Math.min( attributeArray2.length, attributeArray1.length - attributeOffset ); for ( var i = 0, j = attributeOffset; i < length; i ++, j ++ ) { attributeArray1[ j ] = attributeArray2[ i ]; } } return this; }, normalizeNormals: function () { var normals = this.attributes.normal; for ( var i = 0, il = normals.count; i < il; i ++ ) { _vector$4.x = normals.getX( i ); _vector$4.y = normals.getY( i ); _vector$4.z = normals.getZ( i ); _vector$4.normalize(); normals.setXYZ( i, _vector$4.x, _vector$4.y, _vector$4.z ); } }, toNonIndexed: function () { function convertBufferAttribute( attribute, indices ) { var array = attribute.array; var itemSize = attribute.itemSize; var array2 = new array.constructor( indices.length * itemSize ); var index = 0, index2 = 0; for ( var i = 0, l = indices.length; i < l; i ++ ) { index = indices[ i ] * itemSize; for ( var j = 0; j < itemSize; j ++ ) { array2[ index2 ++ ] = array[ index ++ ]; } } return new BufferAttribute( array2, itemSize ); } // if ( this.index === null ) { console.warn( 'THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.' ); return this; } var geometry2 = new BufferGeometry(); var indices = this.index.array; var attributes = this.attributes; // attributes for ( var name in attributes ) { var attribute = attributes[ name ]; var newAttribute = convertBufferAttribute( attribute, indices ); geometry2.setAttribute( name, newAttribute ); } // morph attributes var morphAttributes = this.morphAttributes; for ( name in morphAttributes ) { var morphArray = []; var morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes for ( var i = 0, il = morphAttribute.length; i < il; i ++ ) { var attribute = morphAttribute[ i ]; var newAttribute = convertBufferAttribute( attribute, indices ); morphArray.push( newAttribute ); } geometry2.morphAttributes[ name ] = morphArray; } geometry2.morphTargetsRelative = this.morphTargetsRelative; // groups var groups = this.groups; for ( var i = 0, l = groups.length; i < l; i ++ ) { var group = groups[ i ]; geometry2.addGroup( group.start, group.count, group.materialIndex ); } return geometry2; }, toJSON: function () { var data = { metadata: { version: 4.5, type: 'BufferGeometry', generator: 'BufferGeometry.toJSON' } }; // standard BufferGeometry serialization data.uuid = this.uuid; data.type = this.type; if ( this.name !== '' ) { data.name = this.name; } if ( Object.keys( this.userData ).length > 0 ) { data.userData = this.userData; } if ( this.parameters !== undefined ) { var parameters = this.parameters; for ( var key in parameters ) { if ( parameters[ key ] !== undefined ) { data[ key ] = parameters[ key ]; } } return data; } data.data = { attributes: {} }; var index = this.index; if ( index !== null ) { data.data.index = { type: index.array.constructor.name, array: Array.prototype.slice.call( index.array ) }; } var attributes = this.attributes; for ( var key in attributes ) { var attribute = attributes[ key ]; var attributeData = attribute.toJSON(); if ( attribute.name !== '' ) { attributeData.name = attribute.name; } data.data.attributes[ key ] = attributeData; } var morphAttributes = {}; var hasMorphAttributes = false; for ( var key in this.morphAttributes ) { var attributeArray = this.morphAttributes[ key ]; var array = []; for ( var i = 0, il = attributeArray.length; i < il; i ++ ) { var attribute = attributeArray[ i ]; var attributeData = attribute.toJSON(); if ( attribute.name !== '' ) { attributeData.name = attribute.name; } array.push( attributeData ); } if ( array.length > 0 ) { morphAttributes[ key ] = array; hasMorphAttributes = true; } } if ( hasMorphAttributes ) { data.data.morphAttributes = morphAttributes; data.data.morphTargetsRelative = this.morphTargetsRelative; } var groups = this.groups; if ( groups.length > 0 ) { data.data.groups = JSON.parse( JSON.stringify( groups ) ); } var boundingSphere = this.boundingSphere; if ( boundingSphere !== null ) { data.data.boundingSphere = { center: boundingSphere.center.toArray(), radius: boundingSphere.radius }; } return data; }, clone: function () { /* // Handle primitives var parameters = this.parameters; if ( parameters !== undefined ) { var values = []; for ( var key in parameters ) { values.push( parameters[ key ] ); } var geometry = Object.create( this.constructor.prototype ); this.constructor.apply( geometry, values ); return geometry; } return new this.constructor().copy( this ); */ return new BufferGeometry().copy( this ); }, copy: function ( source ) { var name, i, l; // reset this.index = null; this.attributes = {}; this.morphAttributes = {}; this.groups = []; this.boundingBox = null; this.boundingSphere = null; // name this.name = source.name; // index var index = source.index; if ( index !== null ) { this.setIndex( index.clone() ); } // attributes var attributes = source.attributes; for ( name in attributes ) { var attribute = attributes[ name ]; this.setAttribute( name, attribute.clone() ); } // morph attributes var morphAttributes = source.morphAttributes; for ( name in morphAttributes ) { var array = []; var morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes for ( i = 0, l = morphAttribute.length; i < l; i ++ ) { array.push( morphAttribute[ i ].clone() ); } this.morphAttributes[ name ] = array; } this.morphTargetsRelative = source.morphTargetsRelative; // groups var groups = source.groups; for ( i = 0, l = groups.length; i < l; i ++ ) { var group = groups[ i ]; this.addGroup( group.start, group.count, group.materialIndex ); } // bounding box var boundingBox = source.boundingBox; if ( boundingBox !== null ) { this.boundingBox = boundingBox.clone(); } // bounding sphere var boundingSphere = source.boundingSphere; if ( boundingSphere !== null ) { this.boundingSphere = boundingSphere.clone(); } // draw range this.drawRange.start = source.drawRange.start; this.drawRange.count = source.drawRange.count; // user data this.userData = source.userData; return this; }, dispose: function () { this.dispatchEvent( { type: 'dispose' } ); } } ); /** * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ * @author mikael emtinger / http://gomo.se/ * @author jonobr1 / http://jonobr1.com/ */ var _inverseMatrix = new Matrix4(); var _ray = new Ray(); var _sphere = new Sphere(); var _vA = new Vector3(); var _vB = new Vector3(); var _vC = new Vector3(); var _tempA = new Vector3(); var _tempB = new Vector3(); var _tempC = new Vector3(); var _morphA = new Vector3(); var _morphB = new Vector3(); var _morphC = new Vector3(); var _uvA = new Vector2(); var _uvB = new Vector2(); var _uvC = new Vector2(); var _intersectionPoint = new Vector3(); var _intersectionPointWorld = new Vector3(); function Mesh( geometry, material ) { Object3D.call( this ); this.type = 'Mesh'; this.geometry = geometry !== undefined ? geometry : new BufferGeometry(); this.material = material !== undefined ? material : new MeshBasicMaterial(); this.updateMorphTargets(); } Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), { constructor: Mesh, isMesh: true, copy: function ( source ) { Object3D.prototype.copy.call( this, source ); if ( source.morphTargetInfluences !== undefined ) { this.morphTargetInfluences = source.morphTargetInfluences.slice(); } if ( source.morphTargetDictionary !== undefined ) { this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary ); } return this; }, updateMorphTargets: function () { var geometry = this.geometry; var m, ml, name; if ( geometry.isBufferGeometry ) { var morphAttributes = geometry.morphAttributes; var keys = Object.keys( morphAttributes ); if ( keys.length > 0 ) { var morphAttribute = morphAttributes[ keys[ 0 ] ]; if ( morphAttribute !== undefined ) { this.morphTargetInfluences = []; this.morphTargetDictionary = {}; for ( m = 0, ml = morphAttribute.length; m < ml; m ++ ) { name = morphAttribute[ m ].name || String( m ); this.morphTargetInfluences.push( 0 ); this.morphTargetDictionary[ name ] = m; } } } } else { var morphTargets = geometry.morphTargets; if ( morphTargets !== undefined && morphTargets.length > 0 ) { console.error( 'THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' ); } } }, raycast: function ( raycaster, intersects ) { var geometry = this.geometry; var material = this.material; var matrixWorld = this.matrixWorld; if ( material === undefined ) { return; } // Checking boundingSphere distance to ray if ( geometry.boundingSphere === null ) { geometry.computeBoundingSphere(); } _sphere.copy( geometry.boundingSphere ); _sphere.applyMatrix4( matrixWorld ); if ( raycaster.ray.intersectsSphere( _sphere ) === false ) { return; } // _inverseMatrix.getInverse( matrixWorld ); _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix ); // Check boundingBox before continuing if ( geometry.boundingBox !== null ) { if ( _ray.intersectsBox( geometry.boundingBox ) === false ) { return; } } var intersection; if ( geometry.isBufferGeometry ) { var a, b, c; var index = geometry.index; var position = geometry.attributes.position; var morphPosition = geometry.morphAttributes.position; var morphTargetsRelative = geometry.morphTargetsRelative; var uv = geometry.attributes.uv; var uv2 = geometry.attributes.uv2; var groups = geometry.groups; var drawRange = geometry.drawRange; var i, j, il, jl; var group, groupMaterial; var start, end; if ( index !== null ) { // indexed buffer geometry if ( Array.isArray( material ) ) { for ( i = 0, il = groups.length; i < il; i ++ ) { group = groups[ i ]; groupMaterial = material[ group.materialIndex ]; start = Math.max( group.start, drawRange.start ); end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ); for ( j = start, jl = end; j < jl; j += 3 ) { a = index.getX( j ); b = index.getX( j + 1 ); c = index.getX( j + 2 ); intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ); if ( intersection ) { intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics intersection.face.materialIndex = group.materialIndex; intersects.push( intersection ); } } } } else { start = Math.max( 0, drawRange.start ); end = Math.min( index.count, ( drawRange.start + drawRange.count ) ); for ( i = start, il = end; i < il; i += 3 ) { a = index.getX( i ); b = index.getX( i + 1 ); c = index.getX( i + 2 ); intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ); if ( intersection ) { intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics intersects.push( intersection ); } } } } else if ( position !== undefined ) { // non-indexed buffer geometry if ( Array.isArray( material ) ) { for ( i = 0, il = groups.length; i < il; i ++ ) { group = groups[ i ]; groupMaterial = material[ group.materialIndex ]; start = Math.max( group.start, drawRange.start ); end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ); for ( j = start, jl = end; j < jl; j += 3 ) { a = j; b = j + 1; c = j + 2; intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ); if ( intersection ) { intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics intersection.face.materialIndex = group.materialIndex; intersects.push( intersection ); } } } } else { start = Math.max( 0, drawRange.start ); end = Math.min( position.count, ( drawRange.start + drawRange.count ) ); for ( i = start, il = end; i < il; i += 3 ) { a = i; b = i + 1; c = i + 2; intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ); if ( intersection ) { intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics intersects.push( intersection ); } } } } } else if ( geometry.isGeometry ) { var fvA, fvB, fvC; var isMultiMaterial = Array.isArray( material ); var vertices = geometry.vertices; var faces = geometry.faces; var uvs; var faceVertexUvs = geometry.faceVertexUvs[ 0 ]; if ( faceVertexUvs.length > 0 ) { uvs = faceVertexUvs; } for ( var f = 0, fl = faces.length; f < fl; f ++ ) { var face = faces[ f ]; var faceMaterial = isMultiMaterial ? material[ face.materialIndex ] : material; if ( faceMaterial === undefined ) { continue; } fvA = vertices[ face.a ]; fvB = vertices[ face.b ]; fvC = vertices[ face.c ]; intersection = checkIntersection( this, faceMaterial, raycaster, _ray, fvA, fvB, fvC, _intersectionPoint ); if ( intersection ) { if ( uvs && uvs[ f ] ) { var uvs_f = uvs[ f ]; _uvA.copy( uvs_f[ 0 ] ); _uvB.copy( uvs_f[ 1 ] ); _uvC.copy( uvs_f[ 2 ] ); intersection.uv = Triangle.getUV( _intersectionPoint, fvA, fvB, fvC, _uvA, _uvB, _uvC, new Vector2() ); } intersection.face = face; intersection.faceIndex = f; intersects.push( intersection ); } } } }, clone: function () { return new this.constructor( this.geometry, this.material ).copy( this ); } } ); function checkIntersection( object, material, raycaster, ray, pA, pB, pC, point ) { var intersect; if ( material.side === BackSide ) { intersect = ray.intersectTriangle( pC, pB, pA, true, point ); } else { intersect = ray.intersectTriangle( pA, pB, pC, material.side !== DoubleSide, point ); } if ( intersect === null ) { return null; } _intersectionPointWorld.copy( point ); _intersectionPointWorld.applyMatrix4( object.matrixWorld ); var distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld ); if ( distance < raycaster.near || distance > raycaster.far ) { return null; } return { distance: distance, point: _intersectionPointWorld.clone(), object: object }; } function checkBufferGeometryIntersection( object, material, raycaster, ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ) { _vA.fromBufferAttribute( position, a ); _vB.fromBufferAttribute( position, b ); _vC.fromBufferAttribute( position, c ); var morphInfluences = object.morphTargetInfluences; if ( material.morphTargets && morphPosition && morphInfluences ) { _morphA.set( 0, 0, 0 ); _morphB.set( 0, 0, 0 ); _morphC.set( 0, 0, 0 ); for ( var i = 0, il = morphPosition.length; i < il; i ++ ) { var influence = morphInfluences[ i ]; var morphAttribute = morphPosition[ i ]; if ( influence === 0 ) { continue; } _tempA.fromBufferAttribute( morphAttribute, a ); _tempB.fromBufferAttribute( morphAttribute, b ); _tempC.fromBufferAttribute( morphAttribute, c ); if ( morphTargetsRelative ) { _morphA.addScaledVector( _tempA, influence ); _morphB.addScaledVector( _tempB, influence ); _morphC.addScaledVector( _tempC, influence ); } else { _morphA.addScaledVector( _tempA.sub( _vA ), influence ); _morphB.addScaledVector( _tempB.sub( _vB ), influence ); _morphC.addScaledVector( _tempC.sub( _vC ), influence ); } } _vA.add( _morphA ); _vB.add( _morphB ); _vC.add( _morphC ); } var intersection = checkIntersection( object, material, raycaster, ray, _vA, _vB, _vC, _intersectionPoint ); if ( intersection ) { if ( uv ) { _uvA.fromBufferAttribute( uv, a ); _uvB.fromBufferAttribute( uv, b ); _uvC.fromBufferAttribute( uv, c ); intersection.uv = Triangle.getUV( _intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ); } if ( uv2 ) { _uvA.fromBufferAttribute( uv2, a ); _uvB.fromBufferAttribute( uv2, b ); _uvC.fromBufferAttribute( uv2, c ); intersection.uv2 = Triangle.getUV( _intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ); } var face = new Face3( a, b, c ); Triangle.getNormal( _vA, _vB, _vC, face.normal ); intersection.face = face; } return intersection; } /** * @author mrdoob / http://mrdoob.com/ * @author kile / http://kile.stravaganza.org/ * @author alteredq / http://alteredqualia.com/ * @author mikael emtinger / http://gomo.se/ * @author zz85 / http://www.lab4games.net/zz85/blog * @author bhouston / http://clara.io */ var _geometryId = 0; // Geometry uses even numbers as Id var _m1$3 = new Matrix4(); var _obj$1 = new Object3D(); var _offset$1 = new Vector3(); function Geometry() { Object.defineProperty( this, 'id', { value: _geometryId += 2 } ); this.uuid = MathUtils.generateUUID(); this.name = ''; this.type = 'Geometry'; this.vertices = []; this.colors = []; this.faces = []; this.faceVertexUvs = [[]]; this.morphTargets = []; this.morphNormals = []; this.skinWeights = []; this.skinIndices = []; this.lineDistances = []; this.boundingBox = null; this.boundingSphere = null; // update flags this.elementsNeedUpdate = false; this.verticesNeedUpdate = false; this.uvsNeedUpdate = false; this.normalsNeedUpdate = false; this.colorsNeedUpdate = false; this.lineDistancesNeedUpdate = false; this.groupsNeedUpdate = false; } Geometry.prototype = Object.assign( Object.create( EventDispatcher.prototype ), { constructor: Geometry, isGeometry: true, applyMatrix4: function ( matrix ) { var normalMatrix = new Matrix3().getNormalMatrix( matrix ); for ( var i = 0, il = this.vertices.length; i < il; i ++ ) { var vertex = this.vertices[ i ]; vertex.applyMatrix4( matrix ); } for ( var i = 0, il = this.faces.length; i < il; i ++ ) { var face = this.faces[ i ]; face.normal.applyMatrix3( normalMatrix ).normalize(); for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) { face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize(); } } if ( this.boundingBox !== null ) { this.computeBoundingBox(); } if ( this.boundingSphere !== null ) { this.computeBoundingSphere(); } this.verticesNeedUpdate = true; this.normalsNeedUpdate = true; return this; }, rotateX: function ( angle ) { // rotate geometry around world x-axis _m1$3.makeRotationX( angle ); this.applyMatrix4( _m1$3 ); return this; }, rotateY: function ( angle ) { // rotate geometry around world y-axis _m1$3.makeRotationY( angle ); this.applyMatrix4( _m1$3 ); return this; }, rotateZ: function ( angle ) { // rotate geometry around world z-axis _m1$3.makeRotationZ( angle ); this.applyMatrix4( _m1$3 ); return this; }, translate: function ( x, y, z ) { // translate geometry _m1$3.makeTranslation( x, y, z ); this.applyMatrix4( _m1$3 ); return this; }, scale: function ( x, y, z ) { // scale geometry _m1$3.makeScale( x, y, z ); this.applyMatrix4( _m1$3 ); return this; }, lookAt: function ( vector ) { _obj$1.lookAt( vector ); _obj$1.updateMatrix(); this.applyMatrix4( _obj$1.matrix ); return this; }, fromBufferGeometry: function ( geometry ) { var scope = this; var indices = geometry.index !== null ? geometry.index.array : undefined; var attributes = geometry.attributes; if ( attributes.position === undefined ) { console.error( 'THREE.Geometry.fromBufferGeometry(): Position attribute required for conversion.' ); return this; } var positions = attributes.position.array; var normals = attributes.normal !== undefined ? attributes.normal.array : undefined; var colors = attributes.color !== undefined ? attributes.color.array : undefined; var uvs = attributes.uv !== undefined ? attributes.uv.array : undefined; var uvs2 = attributes.uv2 !== undefined ? attributes.uv2.array : undefined; if ( uvs2 !== undefined ) { this.faceVertexUvs[ 1 ] = []; } for ( var i = 0; i < positions.length; i += 3 ) { scope.vertices.push( new Vector3().fromArray( positions, i ) ); if ( colors !== undefined ) { scope.colors.push( new Color().fromArray( colors, i ) ); } } function addFace( a, b, c, materialIndex ) { var vertexColors = ( colors === undefined ) ? [] : [ scope.colors[ a ].clone(), scope.colors[ b ].clone(), scope.colors[ c ].clone() ]; var vertexNormals = ( normals === undefined ) ? [] : [ new Vector3().fromArray( normals, a * 3 ), new Vector3().fromArray( normals, b * 3 ), new Vector3().fromArray( normals, c * 3 ) ]; var face = new Face3( a, b, c, vertexNormals, vertexColors, materialIndex ); scope.faces.push( face ); if ( uvs !== undefined ) { scope.faceVertexUvs[ 0 ].push( [ new Vector2().fromArray( uvs, a * 2 ), new Vector2().fromArray( uvs, b * 2 ), new Vector2().fromArray( uvs, c * 2 ) ] ); } if ( uvs2 !== undefined ) { scope.faceVertexUvs[ 1 ].push( [ new Vector2().fromArray( uvs2, a * 2 ), new Vector2().fromArray( uvs2, b * 2 ), new Vector2().fromArray( uvs2, c * 2 ) ] ); } } var groups = geometry.groups; if ( groups.length > 0 ) { for ( var i = 0; i < groups.length; i ++ ) { var group = groups[ i ]; var start = group.start; var count = group.count; for ( var j = start, jl = start + count; j < jl; j += 3 ) { if ( indices !== undefined ) { addFace( indices[ j ], indices[ j + 1 ], indices[ j + 2 ], group.materialIndex ); } else { addFace( j, j + 1, j + 2, group.materialIndex ); } } } } else { if ( indices !== undefined ) { for ( var i = 0; i < indices.length; i += 3 ) { addFace( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] ); } } else { for ( var i = 0; i < positions.length / 3; i += 3 ) { addFace( i, i + 1, i + 2 ); } } } this.computeFaceNormals(); if ( geometry.boundingBox !== null ) { this.boundingBox = geometry.boundingBox.clone(); } if ( geometry.boundingSphere !== null ) { this.boundingSphere = geometry.boundingSphere.clone(); } return this; }, center: function () { this.computeBoundingBox(); this.boundingBox.getCenter( _offset$1 ).negate(); this.translate( _offset$1.x, _offset$1.y, _offset$1.z ); return this; }, normalize: function () { this.computeBoundingSphere(); var center = this.boundingSphere.center; var radius = this.boundingSphere.radius; var s = radius === 0 ? 1 : 1.0 / radius; var matrix = new Matrix4(); matrix.set( s, 0, 0, - s * center.x, 0, s, 0, - s * center.y, 0, 0, s, - s * center.z, 0, 0, 0, 1 ); this.applyMatrix4( matrix ); return this; }, computeFaceNormals: function () { var cb = new Vector3(), ab = new Vector3(); for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) { var face = this.faces[ f ]; var vA = this.vertices[ face.a ]; var vB = this.vertices[ face.b ]; var vC = this.vertices[ face.c ]; cb.subVectors( vC, vB ); ab.subVectors( vA, vB ); cb.cross( ab ); cb.normalize(); face.normal.copy( cb ); } }, computeVertexNormals: function ( areaWeighted ) { if ( areaWeighted === undefined ) { areaWeighted = true; } var v, vl, f, fl, face, vertices; vertices = new Array( this.vertices.length ); for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) { vertices[ v ] = new Vector3(); } if ( areaWeighted ) { // vertex normals weighted by triangle areas // http://www.iquilezles.org/www/articles/normals/normals.htm var vA, vB, vC; var cb = new Vector3(), ab = new Vector3(); for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { face = this.faces[ f ]; vA = this.vertices[ face.a ]; vB = this.vertices[ face.b ]; vC = this.vertices[ face.c ]; cb.subVectors( vC, vB ); ab.subVectors( vA, vB ); cb.cross( ab ); vertices[ face.a ].add( cb ); vertices[ face.b ].add( cb ); vertices[ face.c ].add( cb ); } } else { this.computeFaceNormals(); for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { face = this.faces[ f ]; vertices[ face.a ].add( face.normal ); vertices[ face.b ].add( face.normal ); vertices[ face.c ].add( face.normal ); } } for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) { vertices[ v ].normalize(); } for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { face = this.faces[ f ]; var vertexNormals = face.vertexNormals; if ( vertexNormals.length === 3 ) { vertexNormals[ 0 ].copy( vertices[ face.a ] ); vertexNormals[ 1 ].copy( vertices[ face.b ] ); vertexNormals[ 2 ].copy( vertices[ face.c ] ); } else { vertexNormals[ 0 ] = vertices[ face.a ].clone(); vertexNormals[ 1 ] = vertices[ face.b ].clone(); vertexNormals[ 2 ] = vertices[ face.c ].clone(); } } if ( this.faces.length > 0 ) { this.normalsNeedUpdate = true; } }, computeFlatVertexNormals: function () { var f, fl, face; this.computeFaceNormals(); for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { face = this.faces[ f ]; var vertexNormals = face.vertexNormals; if ( vertexNormals.length === 3 ) { vertexNormals[ 0 ].copy( face.normal ); vertexNormals[ 1 ].copy( face.normal ); vertexNormals[ 2 ].copy( face.normal ); } else { vertexNormals[ 0 ] = face.normal.clone(); vertexNormals[ 1 ] = face.normal.clone(); vertexNormals[ 2 ] = face.normal.clone(); } } if ( this.faces.length > 0 ) { this.normalsNeedUpdate = true; } }, computeMorphNormals: function () { var i, il, f, fl, face; // save original normals // - create temp variables on first access // otherwise just copy (for faster repeated calls) for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { face = this.faces[ f ]; if ( ! face.__originalFaceNormal ) { face.__originalFaceNormal = face.normal.clone(); } else { face.__originalFaceNormal.copy( face.normal ); } if ( ! face.__originalVertexNormals ) { face.__originalVertexNormals = []; } for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) { if ( ! face.__originalVertexNormals[ i ] ) { face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone(); } else { face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] ); } } } // use temp geometry to compute face and vertex normals for each morph var tmpGeo = new Geometry(); tmpGeo.faces = this.faces; for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) { // create on first access if ( ! this.morphNormals[ i ] ) { this.morphNormals[ i ] = {}; this.morphNormals[ i ].faceNormals = []; this.morphNormals[ i ].vertexNormals = []; var dstNormalsFace = this.morphNormals[ i ].faceNormals; var dstNormalsVertex = this.morphNormals[ i ].vertexNormals; var faceNormal, vertexNormals; for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { faceNormal = new Vector3(); vertexNormals = { a: new Vector3(), b: new Vector3(), c: new Vector3() }; dstNormalsFace.push( faceNormal ); dstNormalsVertex.push( vertexNormals ); } } var morphNormals = this.morphNormals[ i ]; // set vertices to morph target tmpGeo.vertices = this.morphTargets[ i ].vertices; // compute morph normals tmpGeo.computeFaceNormals(); tmpGeo.computeVertexNormals(); // store morph normals var faceNormal, vertexNormals; for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { face = this.faces[ f ]; faceNormal = morphNormals.faceNormals[ f ]; vertexNormals = morphNormals.vertexNormals[ f ]; faceNormal.copy( face.normal ); vertexNormals.a.copy( face.vertexNormals[ 0 ] ); vertexNormals.b.copy( face.vertexNormals[ 1 ] ); vertexNormals.c.copy( face.vertexNormals[ 2 ] ); } } // restore original normals for ( f = 0, fl = this.faces.length; f < fl; f ++ ) { face = this.faces[ f ]; face.normal = face.__originalFaceNormal; face.vertexNormals = face.__originalVertexNormals; } }, computeBoundingBox: function () { if ( this.boundingBox === null ) { this.boundingBox = new Box3(); } this.boundingBox.setFromPoints( this.vertices ); }, computeBoundingSphere: function () { if ( this.boundingSphere === null ) { this.boundingSphere = new Sphere(); } this.boundingSphere.setFromPoints( this.vertices ); }, merge: function ( geometry, matrix, materialIndexOffset ) { if ( ! ( geometry && geometry.isGeometry ) ) { console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry ); return; } var normalMatrix, vertexOffset = this.vertices.length, vertices1 = this.vertices, vertices2 = geometry.vertices, faces1 = this.faces, faces2 = geometry.faces, colors1 = this.colors, colors2 = geometry.colors; if ( materialIndexOffset === undefined ) { materialIndexOffset = 0; } if ( matrix !== undefined ) { normalMatrix = new Matrix3().getNormalMatrix( matrix ); } // vertices for ( var i = 0, il = vertices2.length; i < il; i ++ ) { var vertex = vertices2[ i ]; var vertexCopy = vertex.clone(); if ( matrix !== undefined ) { vertexCopy.applyMatrix4( matrix ); } vertices1.push( vertexCopy ); } // colors for ( var i = 0, il = colors2.length; i < il; i ++ ) { colors1.push( colors2[ i ].clone() ); } // faces for ( i = 0, il = faces2.length; i < il; i ++ ) { var face = faces2[ i ], faceCopy, normal, color, faceVertexNormals = face.vertexNormals, faceVertexColors = face.vertexColors; faceCopy = new Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset ); faceCopy.normal.copy( face.normal ); if ( normalMatrix !== undefined ) { faceCopy.normal.applyMatrix3( normalMatrix ).normalize(); } for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) { normal = faceVertexNormals[ j ].clone(); if ( normalMatrix !== undefined ) { normal.applyMatrix3( normalMatrix ).normalize(); } faceCopy.vertexNormals.push( normal ); } faceCopy.color.copy( face.color ); for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) { color = faceVertexColors[ j ]; faceCopy.vertexColors.push( color.clone() ); } faceCopy.materialIndex = face.materialIndex + materialIndexOffset; faces1.push( faceCopy ); } // uvs for ( var i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) { var faceVertexUvs2 = geometry.faceVertexUvs[ i ]; if ( this.faceVertexUvs[ i ] === undefined ) { this.faceVertexUvs[ i ] = []; } for ( var j = 0, jl = faceVertexUvs2.length; j < jl; j ++ ) { var uvs2 = faceVertexUvs2[ j ], uvsCopy = []; for ( var k = 0, kl = uvs2.length; k < kl; k ++ ) { uvsCopy.push( uvs2[ k ].clone() ); } this.faceVertexUvs[ i ].push( uvsCopy ); } } }, mergeMesh: function ( mesh ) { if ( ! ( mesh && mesh.isMesh ) ) { console.error( 'THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh ); return; } if ( mesh.matrixAutoUpdate ) { mesh.updateMatrix(); } this.merge( mesh.geometry, mesh.matrix ); }, /* * Checks for duplicate vertices with hashmap. * Duplicated vertices are removed * and faces' vertices are updated. */ mergeVertices: function () { var verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique) var unique = [], changes = []; var v, key; var precisionPoints = 4; // number of decimal points, e.g. 4 for epsilon of 0.0001 var precision = Math.pow( 10, precisionPoints ); var i, il, face; var indices, j, jl; for ( i = 0, il = this.vertices.length; i < il; i ++ ) { v = this.vertices[ i ]; key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision ); if ( verticesMap[ key ] === undefined ) { verticesMap[ key ] = i; unique.push( this.vertices[ i ] ); changes[ i ] = unique.length - 1; } else { //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]); changes[ i ] = changes[ verticesMap[ key ] ]; } } // if faces are completely degenerate after merging vertices, we // have to remove them from the geometry. var faceIndicesToRemove = []; for ( i = 0, il = this.faces.length; i < il; i ++ ) { face = this.faces[ i ]; face.a = changes[ face.a ]; face.b = changes[ face.b ]; face.c = changes[ face.c ]; indices = [ face.a, face.b, face.c ]; // if any duplicate vertices are found in a Face3 // we have to remove the face as nothing can be saved for ( var n = 0; n < 3; n ++ ) { if ( indices[ n ] === indices[ ( n + 1 ) % 3 ] ) { faceIndicesToRemove.push( i ); break; } } } for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) { var idx = faceIndicesToRemove[ i ]; this.faces.splice( idx, 1 ); for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) { this.faceVertexUvs[ j ].splice( idx, 1 ); } } // Use unique set of vertices var diff = this.vertices.length - unique.length; this.vertices = unique; return diff; }, setFromPoints: function ( points ) { this.vertices = []; for ( var i = 0, l = points.length; i < l; i ++ ) { var point = points[ i ]; this.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) ); } return this; }, sortFacesByMaterialIndex: function () { var faces = this.faces; var length = faces.length; // tag faces for ( var i = 0; i < length; i ++ ) { faces[ i ]._id = i; } // sort faces function materialIndexSort( a, b ) { return a.materialIndex - b.materialIndex; } faces.sort( materialIndexSort ); // sort uvs var uvs1 = this.faceVertexUvs[ 0 ]; var uvs2 = this.faceVertexUvs[ 1 ]; var newUvs1, newUvs2; if ( uvs1 && uvs1.length === length ) { newUvs1 = []; } if ( uvs2 && uvs2.length === length ) { newUvs2 = []; } for ( var i = 0; i < length; i ++ ) { var id = faces[ i ]._id; if ( newUvs1 ) { newUvs1.push( uvs1[ id ] ); } if ( newUvs2 ) { newUvs2.push( uvs2[ id ] ); } } if ( newUvs1 ) { this.faceVertexUvs[ 0 ] = newUvs1; } if ( newUvs2 ) { this.faceVertexUvs[ 1 ] = newUvs2; } }, toJSON: function () { var data = { metadata: { version: 4.5, type: 'Geometry', generator: 'Geometry.toJSON' } }; // standard Geometry serialization data.uuid = this.uuid; data.type = this.type; if ( this.name !== '' ) { data.name = this.name; } if ( this.parameters !== undefined ) { var parameters = this.parameters; for ( var key in parameters ) { if ( parameters[ key ] !== undefined ) { data[ key ] = parameters[ key ]; } } return data; } var vertices = []; for ( var i = 0; i < this.vertices.length; i ++ ) { var vertex = this.vertices[ i ]; vertices.push( vertex.x, vertex.y, vertex.z ); } var faces = []; var normals = []; var normalsHash = {}; var colors = []; var colorsHash = {}; var uvs = []; var uvsHash = {}; for ( var i = 0; i < this.faces.length; i ++ ) { var face = this.faces[ i ]; var hasMaterial = true; var hasFaceUv = false; // deprecated var hasFaceVertexUv = this.faceVertexUvs[ 0 ][ i ] !== undefined; var hasFaceNormal = face.normal.length() > 0; var hasFaceVertexNormal = face.vertexNormals.length > 0; var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1; var hasFaceVertexColor = face.vertexColors.length > 0; var faceType = 0; faceType = setBit( faceType, 0, 0 ); // isQuad faceType = setBit( faceType, 1, hasMaterial ); faceType = setBit( faceType, 2, hasFaceUv ); faceType = setBit( faceType, 3, hasFaceVertexUv ); faceType = setBit( faceType, 4, hasFaceNormal ); faceType = setBit( faceType, 5, hasFaceVertexNormal ); faceType = setBit( faceType, 6, hasFaceColor ); faceType = setBit( faceType, 7, hasFaceVertexColor ); faces.push( faceType ); faces.push( face.a, face.b, face.c ); faces.push( face.materialIndex ); if ( hasFaceVertexUv ) { var faceVertexUvs = this.faceVertexUvs[ 0 ][ i ]; faces.push( getUvIndex( faceVertexUvs[ 0 ] ), getUvIndex( faceVertexUvs[ 1 ] ), getUvIndex( faceVertexUvs[ 2 ] ) ); } if ( hasFaceNormal ) { faces.push( getNormalIndex( face.normal ) ); } if ( hasFaceVertexNormal ) { var vertexNormals = face.vertexNormals; faces.push( getNormalIndex( vertexNormals[ 0 ] ), getNormalIndex( vertexNormals[ 1 ] ), getNormalIndex( vertexNormals[ 2 ] ) ); } if ( hasFaceColor ) { faces.push( getColorIndex( face.color ) ); } if ( hasFaceVertexColor ) { var vertexColors = face.vertexColors; faces.push( getColorIndex( vertexColors[ 0 ] ), getColorIndex( vertexColors[ 1 ] ), getColorIndex( vertexColors[ 2 ] ) ); } } function setBit( value, position, enabled ) { return enabled ? value | ( 1 << position ) : value & ( ~ ( 1 << position ) ); } function getNormalIndex( normal ) { var hash = normal.x.toString() + normal.y.toString() + normal.z.toString(); if ( normalsHash[ hash ] !== undefined ) { return normalsHash[ hash ]; } normalsHash[ hash ] = normals.length / 3; normals.push( normal.x, normal.y, normal.z ); return normalsHash[ hash ]; } function getColorIndex( color ) { var hash = color.r.toString() + color.g.toString() + color.b.toString(); if ( colorsHash[ hash ] !== undefined ) { return colorsHash[ hash ]; } colorsHash[ hash ] = colors.length; colors.push( color.getHex() ); return colorsHash[ hash ]; } function getUvIndex( uv ) { var hash = uv.x.toString() + uv.y.toString(); if ( uvsHash[ hash ] !== undefined ) { return uvsHash[ hash ]; } uvsHash[ hash ] = uvs.length / 2; uvs.push( uv.x, uv.y ); return uvsHash[ hash ]; } data.data = {}; data.data.vertices = vertices; data.data.normals = normals; if ( colors.length > 0 ) { data.data.colors = colors; } if ( uvs.length > 0 ) { data.data.uvs = [ uvs ]; } // temporal backward compatibility data.data.faces = faces; return data; }, clone: function () { /* // Handle primitives var parameters = this.parameters; if ( parameters !== undefined ) { var values = []; for ( var key in parameters ) { values.push( parameters[ key ] ); } var geometry = Object.create( this.constructor.prototype ); this.constructor.apply( geometry, values ); return geometry; } return new this.constructor().copy( this ); */ return new Geometry().copy( this ); }, copy: function ( source ) { var i, il, j, jl, k, kl; // reset this.vertices = []; this.colors = []; this.faces = []; this.faceVertexUvs = [[]]; this.morphTargets = []; this.morphNormals = []; this.skinWeights = []; this.skinIndices = []; this.lineDistances = []; this.boundingBox = null; this.boundingSphere = null; // name this.name = source.name; // vertices var vertices = source.vertices; for ( i = 0, il = vertices.length; i < il; i ++ ) { this.vertices.push( vertices[ i ].clone() ); } // colors var colors = source.colors; for ( i = 0, il = colors.length; i < il; i ++ ) { this.colors.push( colors[ i ].clone() ); } // faces var faces = source.faces; for ( i = 0, il = faces.length; i < il; i ++ ) { this.faces.push( faces[ i ].clone() ); } // face vertex uvs for ( i = 0, il = source.faceVertexUvs.length; i < il; i ++ ) { var faceVertexUvs = source.faceVertexUvs[ i ]; if ( this.faceVertexUvs[ i ] === undefined ) { this.faceVertexUvs[ i ] = []; } for ( j = 0, jl = faceVertexUvs.length; j < jl; j ++ ) { var uvs = faceVertexUvs[ j ], uvsCopy = []; for ( k = 0, kl = uvs.length; k < kl; k ++ ) { var uv = uvs[ k ]; uvsCopy.push( uv.clone() ); } this.faceVertexUvs[ i ].push( uvsCopy ); } } // morph targets var morphTargets = source.morphTargets; for ( i = 0, il = morphTargets.length; i < il; i ++ ) { var morphTarget = {}; morphTarget.name = morphTargets[ i ].name; // vertices if ( morphTargets[ i ].vertices !== undefined ) { morphTarget.vertices = []; for ( j = 0, jl = morphTargets[ i ].vertices.length; j < jl; j ++ ) { morphTarget.vertices.push( morphTargets[ i ].vertices[ j ].clone() ); } } // normals if ( morphTargets[ i ].normals !== undefined ) { morphTarget.normals = []; for ( j = 0, jl = morphTargets[ i ].normals.length; j < jl; j ++ ) { morphTarget.normals.push( morphTargets[ i ].normals[ j ].clone() ); } } this.morphTargets.push( morphTarget ); } // morph normals var morphNormals = source.morphNormals; for ( i = 0, il = morphNormals.length; i < il; i ++ ) { var morphNormal = {}; // vertex normals if ( morphNormals[ i ].vertexNormals !== undefined ) { morphNormal.vertexNormals = []; for ( j = 0, jl = morphNormals[ i ].vertexNormals.length; j < jl; j ++ ) { var srcVertexNormal = morphNormals[ i ].vertexNormals[ j ]; var destVertexNormal = {}; destVertexNormal.a = srcVertexNormal.a.clone(); destVertexNormal.b = srcVertexNormal.b.clone(); destVertexNormal.c = srcVertexNormal.c.clone(); morphNormal.vertexNormals.push( destVertexNormal ); } } // face normals if ( morphNormals[ i ].faceNormals !== undefined ) { morphNormal.faceNormals = []; for ( j = 0, jl = morphNormals[ i ].faceNormals.length; j < jl; j ++ ) { morphNormal.faceNormals.push( morphNormals[ i ].faceNormals[ j ].clone() ); } } this.morphNormals.push( morphNormal ); } // skin weights var skinWeights = source.skinWeights; for ( i = 0, il = skinWeights.length; i < il; i ++ ) { this.skinWeights.push( skinWeights[ i ].clone() ); } // skin indices var skinIndices = source.skinIndices; for ( i = 0, il = skinIndices.length; i < il; i ++ ) { this.skinIndices.push( skinIndices[ i ].clone() ); } // line distances var lineDistances = source.lineDistances; for ( i = 0, il = lineDistances.length; i < il; i ++ ) { this.lineDistances.push( lineDistances[ i ] ); } // bounding box var boundingBox = source.boundingBox; if ( boundingBox !== null ) { this.boundingBox = boundingBox.clone(); } // bounding sphere var boundingSphere = source.boundingSphere; if ( boundingSphere !== null ) { this.boundingSphere = boundingSphere.clone(); } // update flags this.elementsNeedUpdate = source.elementsNeedUpdate; this.verticesNeedUpdate = source.verticesNeedUpdate; this.uvsNeedUpdate = source.uvsNeedUpdate; this.normalsNeedUpdate = source.normalsNeedUpdate; this.colorsNeedUpdate = source.colorsNeedUpdate; this.lineDistancesNeedUpdate = source.lineDistancesNeedUpdate; this.groupsNeedUpdate = source.groupsNeedUpdate; return this; }, dispose: function () { this.dispatchEvent( { type: 'dispose' } ); } } ); /** * @author mrdoob / http://mrdoob.com/ * @author Mugen87 / https://github.com/Mugen87 */ // BoxGeometry var BoxGeometry = /*@__PURE__*/(function (Geometry) { function BoxGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) { Geometry.call(this); this.type = 'BoxGeometry'; this.parameters = { width: width, height: height, depth: depth, widthSegments: widthSegments, heightSegments: heightSegments, depthSegments: depthSegments }; this.fromBufferGeometry( new BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) ); this.mergeVertices(); } if ( Geometry ) BoxGeometry.__proto__ = Geometry; BoxGeometry.prototype = Object.create( Geometry && Geometry.prototype ); BoxGeometry.prototype.constructor = BoxGeometry; return BoxGeometry; }(Geometry)); // BoxBufferGeometry var BoxBufferGeometry = /*@__PURE__*/(function (BufferGeometry) { function BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) { BufferGeometry.call(this); this.type = 'BoxBufferGeometry'; this.parameters = { width: width, height: height, depth: depth, widthSegments: widthSegments, heightSegments: heightSegments, depthSegments: depthSegments }; var scope = this; width = width || 1; height = height || 1; depth = depth || 1; // segments widthSegments = Math.floor( widthSegments ) || 1; heightSegments = Math.floor( heightSegments ) || 1; depthSegments = Math.floor( depthSegments ) || 1; // buffers var indices = []; var vertices = []; var normals = []; var uvs = []; // helper variables var numberOfVertices = 0; var groupStart = 0; // build each side of the box geometry buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz // build geometry this.setIndex( indices ); this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) { var segmentWidth = width / gridX; var segmentHeight = height / gridY; var widthHalf = width / 2; var heightHalf = height / 2; var depthHalf = depth / 2; var gridX1 = gridX + 1; var gridY1 = gridY + 1; var vertexCounter = 0; var groupCount = 0; var ix, iy; var vector = new Vector3(); // generate vertices, normals and uvs for ( iy = 0; iy < gridY1; iy ++ ) { var y = iy * segmentHeight - heightHalf; for ( ix = 0; ix < gridX1; ix ++ ) { var x = ix * segmentWidth - widthHalf; // set values to correct vector component vector[ u ] = x * udir; vector[ v ] = y * vdir; vector[ w ] = depthHalf; // now apply vector to vertex buffer vertices.push( vector.x, vector.y, vector.z ); // set values to correct vector component vector[ u ] = 0; vector[ v ] = 0; vector[ w ] = depth > 0 ? 1 : - 1; // now apply vector to normal buffer normals.push( vector.x, vector.y, vector.z ); // uvs uvs.push( ix / gridX ); uvs.push( 1 - ( iy / gridY ) ); // counters vertexCounter += 1; } } // indices // 1. you need three indices to draw a single face // 2. a single segment consists of two faces // 3. so we need to generate six (2*3) indices per segment for ( iy = 0; iy < gridY; iy ++ ) { for ( ix = 0; ix < gridX; ix ++ ) { var a = numberOfVertices + ix + gridX1 * iy; var b = numberOfVertices + ix + gridX1 * ( iy + 1 ); var c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 ); var d = numberOfVertices + ( ix + 1 ) + gridX1 * iy; // faces indices.push( a, b, d ); indices.push( b, c, d ); // increase counter groupCount += 6; } } // add a group to the geometry. this will ensure multi material support scope.addGroup( groupStart, groupCount, materialIndex ); // calculate new start value for groups groupStart += groupCount; // update total number of vertices numberOfVertices += vertexCounter; } } if ( BufferGeometry ) BoxBufferGeometry.__proto__ = BufferGeometry; BoxBufferGeometry.prototype = Object.create( BufferGeometry && BufferGeometry.prototype ); BoxBufferGeometry.prototype.constructor = BoxBufferGeometry; return BoxBufferGeometry; }(BufferGeometry)); /** * Uniform Utilities */ function cloneUniforms( src ) { var dst = {}; for ( var u in src ) { dst[ u ] = {}; for ( var p in src[ u ] ) { var property = src[ u ][ p ]; if ( property && ( property.isColor || property.isMatrix3 || property.isMatrix4 || property.isVector2 || property.isVector3 || property.isVector4 || property.isTexture ) ) { dst[ u ][ p ] = property.clone(); } else if ( Array.isArray( property ) ) { dst[ u ][ p ] = property.slice(); } else { dst[ u ][ p ] = property; } } } return dst; } function mergeUniforms( uniforms ) { var merged = {}; for ( var u = 0; u < uniforms.length; u ++ ) { var tmp = cloneUniforms( uniforms[ u ] ); for ( var p in tmp ) { merged[ p ] = tmp[ p ]; } } return merged; } // Legacy var UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms }; var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}"; var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}"; /** * @author alteredq / http://alteredqualia.com/ * * parameters = { * defines: { "label" : "value" }, * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } }, * * fragmentShader: , * vertexShader: , * * wireframe: , * wireframeLinewidth: , * * lights: , * * skinning: , * morphTargets: , * morphNormals: * } */ function ShaderMaterial( parameters ) { Material.call( this ); this.type = 'ShaderMaterial'; this.defines = {}; this.uniforms = {}; this.vertexShader = default_vertex; this.fragmentShader = default_fragment; this.linewidth = 1; this.wireframe = false; this.wireframeLinewidth = 1; this.fog = false; // set to use scene fog this.lights = false; // set to use scene lights this.clipping = false; // set to use user-defined clipping planes this.skinning = false; // set to use skinning attribute streams this.morphTargets = false; // set to use morph targets this.morphNormals = false; // set to use morph normals this.extensions = { derivatives: false, // set to use derivatives fragDepth: false, // set to use fragment depth values drawBuffers: false, // set to use draw buffers shaderTextureLOD: false // set to use shader texture LOD }; // When rendered geometry doesn't include these attributes but the material does, // use these default values in WebGL. This avoids errors when buffer data is missing. this.defaultAttributeValues = { 'color': [ 1, 1, 1 ], 'uv': [ 0, 0 ], 'uv2': [ 0, 0 ] }; this.index0AttributeName = undefined; this.uniformsNeedUpdate = false; if ( parameters !== undefined ) { if ( parameters.attributes !== undefined ) { console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' ); } this.setValues( parameters ); } } ShaderMaterial.prototype = Object.create( Material.prototype ); ShaderMaterial.prototype.constructor = ShaderMaterial; ShaderMaterial.prototype.isShaderMaterial = true; ShaderMaterial.prototype.copy = function ( source ) { Material.prototype.copy.call( this, source ); this.fragmentShader = source.fragmentShader; this.vertexShader = source.vertexShader; this.uniforms = cloneUniforms( source.uniforms ); this.defines = Object.assign( {}, source.defines ); this.wireframe = source.wireframe; this.wireframeLinewidth = source.wireframeLinewidth; this.lights = source.lights; this.clipping = source.clipping; this.skinning = source.skinning; this.morphTargets = source.morphTargets; this.morphNormals = source.morphNormals; this.extensions = source.extensions; return this; }; ShaderMaterial.prototype.toJSON = function ( meta ) { var data = Material.prototype.toJSON.call( this, meta ); data.uniforms = {}; for ( var name in this.uniforms ) { var uniform = this.uniforms[ name ]; var value = uniform.value; if ( value && value.isTexture ) { data.uniforms[ name ] = { type: 't', value: value.toJSON( meta ).uuid }; } else if ( value && value.isColor ) { data.uniforms[ name ] = { type: 'c', value: value.getHex() }; } else if ( value && value.isVector2 ) { data.uniforms[ name ] = { type: 'v2', value: value.toArray() }; } else if ( value && value.isVector3 ) { data.uniforms[ name ] = { type: 'v3', value: value.toArray() }; } else if ( value && value.isVector4 ) { data.uniforms[ name ] = { type: 'v4', value: value.toArray() }; } else if ( value && value.isMatrix3 ) { data.uniforms[ name ] = { type: 'm3', value: value.toArray() }; } else if ( value && value.isMatrix4 ) { data.uniforms[ name ] = { type: 'm4', value: value.toArray() }; } else { data.uniforms[ name ] = { value: value }; // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far } } if ( Object.keys( this.defines ).length > 0 ) { data.defines = this.defines; } data.vertexShader = this.vertexShader; data.fragmentShader = this.fragmentShader; var extensions = {}; for ( var key in this.extensions ) { if ( this.extensions[ key ] === true ) { extensions[ key ] = true; } } if ( Object.keys( extensions ).length > 0 ) { data.extensions = extensions; } return data; }; /** * @author mrdoob / http://mrdoob.com/ * @author mikael emtinger / http://gomo.se/ * @author WestLangley / http://github.com/WestLangley */ function Camera() { Object3D.call( this ); this.type = 'Camera'; this.matrixWorldInverse = new Matrix4(); this.projectionMatrix = new Matrix4(); this.projectionMatrixInverse = new Matrix4(); } Camera.prototype = Object.assign( Object.create( Object3D.prototype ), { constructor: Camera, isCamera: true, copy: function ( source, recursive ) { Object3D.prototype.copy.call( this, source, recursive ); this.matrixWorldInverse.copy( source.matrixWorldInverse ); this.projectionMatrix.copy( source.projectionMatrix ); this.projectionMatrixInverse.copy( source.projectionMatrixInverse ); return this; }, getWorldDirection: function ( target ) { if ( target === undefined ) { console.warn( 'THREE.Camera: .getWorldDirection() target is now required' ); target = new Vector3(); } this.updateMatrixWorld( true ); var e = this.matrixWorld.elements; return target.set( - e[ 8 ], - e[ 9 ], - e[ 10 ] ).normalize(); }, updateMatrixWorld: function ( force ) { Object3D.prototype.updateMatrixWorld.call( this, force ); this.matrixWorldInverse.getInverse( this.matrixWorld ); }, updateWorldMatrix: function ( updateParents, updateChildren ) { Object3D.prototype.updateWorldMatrix.call( this, updateParents, updateChildren ); this.matrixWorldInverse.getInverse( this.matrixWorld ); }, clone: function () { return new this.constructor().copy( this ); } } ); /** * @author mrdoob / http://mrdoob.com/ * @author greggman / http://games.greggman.com/ * @author zz85 / http://www.lab4games.net/zz85/blog * @author tschw */ function PerspectiveCamera( fov, aspect, near, far ) { Camera.call( this ); this.type = 'PerspectiveCamera'; this.fov = fov !== undefined ? fov : 50; this.zoom = 1; this.near = near !== undefined ? near : 0.1; this.far = far !== undefined ? far : 2000; this.focus = 10; this.aspect = aspect !== undefined ? aspect : 1; this.view = null; this.filmGauge = 35; // width of the film (default in millimeters) this.filmOffset = 0; // horizontal film offset (same unit as gauge) this.updateProjectionMatrix(); } PerspectiveCamera.prototype = Object.assign( Object.create( Camera.prototype ), { constructor: PerspectiveCamera, isPerspectiveCamera: true, copy: function ( source, recursive ) { Camera.prototype.copy.call( this, source, recursive ); this.fov = source.fov; this.zoom = source.zoom; this.near = source.near; this.far = source.far; this.focus = source.focus; this.aspect = source.aspect; this.view = source.view === null ? null : Object.assign( {}, source.view ); this.filmGauge = source.filmGauge; this.filmOffset = source.filmOffset; return this; }, /** * Sets the FOV by focal length in respect to the current .filmGauge. * * The default film gauge is 35, so that the focal length can be specified for * a 35mm (full frame) camera. * * Values for focal length and film gauge must have the same unit. */ setFocalLength: function ( focalLength ) { // see http://www.bobatkins.com/photography/technical/field_of_view.html var vExtentSlope = 0.5 * this.getFilmHeight() / focalLength; this.fov = MathUtils.RAD2DEG * 2 * Math.atan( vExtentSlope ); this.updateProjectionMatrix(); }, /** * Calculates the focal length from the current .fov and .filmGauge. */ getFocalLength: function () { var vExtentSlope = Math.tan( MathUtils.DEG2RAD * 0.5 * this.fov ); return 0.5 * this.getFilmHeight() / vExtentSlope; }, getEffectiveFOV: function () { return MathUtils.RAD2DEG * 2 * Math.atan( Math.tan( MathUtils.DEG2RAD * 0.5 * this.fov ) / this.zoom ); }, getFilmWidth: function () { // film not completely covered in portrait format (aspect < 1) return this.filmGauge * Math.min( this.aspect, 1 ); }, getFilmHeight: function () { // film not completely covered in landscape format (aspect > 1) return this.filmGauge / Math.max( this.aspect, 1 ); }, /** * Sets an offset in a larger frustum. This is useful for multi-window or * multi-monitor/multi-machine setups. * * For example, if you have 3x2 monitors and each monitor is 1920x1080 and * the monitors are in grid like this * * +---+---+---+ * | A | B | C | * +---+---+---+ * | D | E | F | * +---+---+---+ * * then for each monitor you would call it like this * * var w = 1920; * var h = 1080; * var fullWidth = w * 3; * var fullHeight = h * 2; * * --A-- * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h ); * --B-- * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h ); * --C-- * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h ); * --D-- * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h ); * --E-- * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h ); * --F-- * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h ); * * Note there is no reason monitors have to be the same size or in a grid. */ setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) { this.aspect = fullWidth / fullHeight; if ( this.view === null ) { this.view = { enabled: true, fullWidth: 1, fullHeight: 1, offsetX: 0, offsetY: 0, width: 1, height: 1 }; } this.view.enabled = true; this.view.fullWidth = fullWidth; this.view.fullHeight = fullHeight; this.view.offsetX = x; this.view.offsetY = y; this.view.width = width; this.view.height = height; this.updateProjectionMatrix(); }, clearViewOffset: function () { if ( this.view !== null ) { this.view.enabled = false; } this.updateProjectionMatrix(); }, updateProjectionMatrix: function () { var near = this.near, top = near * Math.tan( MathUtils.DEG2RAD * 0.5 * this.fov ) / this.zoom, height = 2 * top, width = this.aspect * height, left = - 0.5 * width, view = this.view; if ( this.view !== null && this.view.enabled ) { var fullWidth = view.fullWidth, fullHeight = view.fullHeight; left += view.offsetX * width / fullWidth; top -= view.offsetY * height / fullHeight; width *= view.width / fullWidth; height *= view.height / fullHeight; } var skew = this.filmOffset; if ( skew !== 0 ) { left += near * skew / this.getFilmWidth(); } this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far ); this.projectionMatrixInverse.getInverse( this.projectionMatrix ); }, toJSON: function ( meta ) { var data = Object3D.prototype.toJSON.call( this, meta ); data.object.fov = this.fov; data.object.zoom = this.zoom; data.object.near = this.near; data.object.far = this.far; data.object.focus = this.focus; data.object.aspect = this.aspect; if ( this.view !== null ) { data.object.view = Object.assign( {}, this.view ); } data.object.filmGauge = this.filmGauge; data.object.filmOffset = this.filmOffset; return data; } } ); /** * Camera for rendering cube maps * - renders scene into axis-aligned cube * * @author alteredq / http://alteredqualia.com/ */ var fov = 90, aspect = 1; function CubeCamera( near, far, cubeResolution, options ) { Object3D.call( this ); this.type = 'CubeCamera'; var cameraPX = new PerspectiveCamera( fov, aspect, near, far ); cameraPX.up.set( 0, - 1, 0 ); cameraPX.lookAt( new Vector3( 1, 0, 0 ) ); this.add( cameraPX ); var cameraNX = new PerspectiveCamera( fov, aspect, near, far ); cameraNX.up.set( 0, - 1, 0 ); cameraNX.lookAt( new Vector3( - 1, 0, 0 ) ); this.add( cameraNX ); var cameraPY = new PerspectiveCamera( fov, aspect, near, far ); cameraPY.up.set( 0, 0, 1 ); cameraPY.lookAt( new Vector3( 0, 1, 0 ) ); this.add( cameraPY ); var cameraNY = new PerspectiveCamera( fov, aspect, near, far ); cameraNY.up.set( 0, 0, - 1 ); cameraNY.lookAt( new Vector3( 0, - 1, 0 ) ); this.add( cameraNY ); var cameraPZ = new PerspectiveCamera( fov, aspect, near, far ); cameraPZ.up.set( 0, - 1, 0 ); cameraPZ.lookAt( new Vector3( 0, 0, 1 ) ); this.add( cameraPZ ); var cameraNZ = new PerspectiveCamera( fov, aspect, near, far ); cameraNZ.up.set( 0, - 1, 0 ); cameraNZ.lookAt( new Vector3( 0, 0, - 1 ) ); this.add( cameraNZ ); options = options || { format: RGBFormat, magFilter: LinearFilter, minFilter: LinearFilter }; this.renderTarget = new WebGLCubeRenderTarget( cubeResolution, options ); this.renderTarget.texture.name = "CubeCamera"; this.update = function ( renderer, scene ) { if ( this.parent === null ) { this.updateMatrixWorld(); } var currentRenderTarget = renderer.getRenderTarget(); var renderTarget = this.renderTarget; var generateMipmaps = renderTarget.texture.generateMipmaps; renderTarget.texture.generateMipmaps = false; renderer.setRenderTarget( renderTarget, 0 ); renderer.render( scene, cameraPX ); renderer.setRenderTarget( renderTarget, 1 ); renderer.render( scene, cameraNX ); renderer.setRenderTarget( renderTarget, 2 ); renderer.render( scene, cameraPY ); renderer.setRenderTarget( renderTarget, 3 ); renderer.render( scene, cameraNY ); renderer.setRenderTarget( renderTarget, 4 ); renderer.render( scene, cameraPZ ); renderTarget.texture.generateMipmaps = generateMipmaps; renderer.setRenderTarget( renderTarget, 5 ); renderer.render( scene, cameraNZ ); renderer.setRenderTarget( currentRenderTarget ); }; this.clear = function ( renderer, color, depth, stencil ) { var currentRenderTarget = renderer.getRenderTarget(); var renderTarget = this.renderTarget; for ( var i = 0; i < 6; i ++ ) { renderer.setRenderTarget( renderTarget, i ); renderer.clear( color, depth, stencil ); } renderer.setRenderTarget( currentRenderTarget ); }; } CubeCamera.prototype = Object.create( Object3D.prototype ); CubeCamera.prototype.constructor = CubeCamera; /** * @author alteredq / http://alteredqualia.com * @author WestLangley / http://github.com/WestLangley */ function WebGLCubeRenderTarget( size, options, dummy ) { if ( Number.isInteger( options ) ) { console.warn( 'THREE.WebGLCubeRenderTarget: constructor signature is now WebGLCubeRenderTarget( size, options )' ); options = dummy; } WebGLRenderTarget.call( this, size, size, options ); } WebGLCubeRenderTarget.prototype = Object.create( WebGLRenderTarget.prototype ); WebGLCubeRenderTarget.prototype.constructor = WebGLCubeRenderTarget; WebGLCubeRenderTarget.prototype.isWebGLCubeRenderTarget = true; WebGLCubeRenderTarget.prototype.fromEquirectangularTexture = function ( renderer, texture ) { this.texture.type = texture.type; this.texture.format = texture.format; this.texture.encoding = texture.encoding; var scene = new Scene(); var shader = { uniforms: { tEquirect: { value: null }, }, vertexShader: [ "varying vec3 vWorldDirection;", "vec3 transformDirection( in vec3 dir, in mat4 matrix ) {", " return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );", "}", "void main() {", " vWorldDirection = transformDirection( position, modelMatrix );", " #include ", " #include ", "}" ].join( '\n' ), fragmentShader: [ "uniform sampler2D tEquirect;", "varying vec3 vWorldDirection;", "#define RECIPROCAL_PI 0.31830988618", "#define RECIPROCAL_PI2 0.15915494", "void main() {", " vec3 direction = normalize( vWorldDirection );", " vec2 sampleUV;", " sampleUV.y = asin( clamp( direction.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;", " sampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;", " gl_FragColor = texture2D( tEquirect, sampleUV );", "}" ].join( '\n' ), }; var material = new ShaderMaterial( { type: 'CubemapFromEquirect', uniforms: cloneUniforms( shader.uniforms ), vertexShader: shader.vertexShader, fragmentShader: shader.fragmentShader, side: BackSide, blending: NoBlending } ); material.uniforms.tEquirect.value = texture; var mesh = new Mesh( new BoxBufferGeometry( 5, 5, 5 ), material ); scene.add( mesh ); var camera = new CubeCamera( 1, 10, 1 ); camera.renderTarget = this; camera.renderTarget.texture.name = 'CubeCameraTexture'; camera.update( renderer, scene ); mesh.geometry.dispose(); mesh.material.dispose(); return this; }; /** * @author alteredq / http://alteredqualia.com/ */ function DataTexture( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) { Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); this.image = { data: data || null, width: width || 1, height: height || 1 }; this.magFilter = magFilter !== undefined ? magFilter : NearestFilter; this.minFilter = minFilter !== undefined ? minFilter : NearestFilter; this.generateMipmaps = false; this.flipY = false; this.unpackAlignment = 1; this.needsUpdate = true; } DataTexture.prototype = Object.create( Texture.prototype ); DataTexture.prototype.constructor = DataTexture; DataTexture.prototype.isDataTexture = true; /** * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ * @author bhouston / http://clara.io */ var _sphere$1 = new Sphere(); var _vector$5 = new Vector3(); function Frustum( p0, p1, p2, p3, p4, p5 ) { this.planes = [ ( p0 !== undefined ) ? p0 : new Plane(), ( p1 !== undefined ) ? p1 : new Plane(), ( p2 !== undefined ) ? p2 : new Plane(), ( p3 !== undefined ) ? p3 : new Plane(), ( p4 !== undefined ) ? p4 : new Plane(), ( p5 !== undefined ) ? p5 : new Plane() ]; } Object.assign( Frustum.prototype, { set: function ( p0, p1, p2, p3, p4, p5 ) { var planes = this.planes; planes[ 0 ].copy( p0 ); planes[ 1 ].copy( p1 ); planes[ 2 ].copy( p2 ); planes[ 3 ].copy( p3 ); planes[ 4 ].copy( p4 ); planes[ 5 ].copy( p5 ); return this; }, clone: function () { return new this.constructor().copy( this ); }, copy: function ( frustum ) { var planes = this.planes; for ( var i = 0; i < 6; i ++ ) { planes[ i ].copy( frustum.planes[ i ] ); } return this; }, setFromProjectionMatrix: function ( m ) { var planes = this.planes; var me = m.elements; var me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ]; var me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ]; var me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ]; var me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ]; planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize(); planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize(); planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize(); planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize(); planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize(); planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize(); return this; }, intersectsObject: function ( object ) { var geometry = object.geometry; if ( geometry.boundingSphere === null ) { geometry.computeBoundingSphere(); } _sphere$1.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld ); return this.intersectsSphere( _sphere$1 ); }, intersectsSprite: function ( sprite ) { _sphere$1.center.set( 0, 0, 0 ); _sphere$1.radius = 0.7071067811865476; _sphere$1.applyMatrix4( sprite.matrixWorld ); return this.intersectsSphere( _sphere$1 ); }, intersectsSphere: function ( sphere ) { var planes = this.planes; var center = sphere.center; var negRadius = - sphere.radius; for ( var i = 0; i < 6; i ++ ) { var distance = planes[ i ].distanceToPoint( center ); if ( distance < negRadius ) { return false; } } return true; }, intersectsBox: function ( box ) { var planes = this.planes; for ( var i = 0; i < 6; i ++ ) { var plane = planes[ i ]; // corner at max distance _vector$5.x = plane.normal.x > 0 ? box.max.x : box.min.x; _vector$5.y = plane.normal.y > 0 ? box.max.y : box.min.y; _vector$5.z = plane.normal.z > 0 ? box.max.z : box.min.z; if ( plane.distanceToPoint( _vector$5 ) < 0 ) { return false; } } return true; }, containsPoint: function ( point ) { var planes = this.planes; for ( var i = 0; i < 6; i ++ ) { if ( planes[ i ].distanceToPoint( point ) < 0 ) { return false; } } return true; } } ); /** * Uniforms library for shared webgl shaders */ var UniformsLib = { common: { diffuse: { value: new Color( 0xeeeeee ) }, opacity: { value: 1.0 }, map: { value: null }, uvTransform: { value: new Matrix3() }, uv2Transform: { value: new Matrix3() }, alphaMap: { value: null }, }, specularmap: { specularMap: { value: null }, }, envmap: { envMap: { value: null }, flipEnvMap: { value: - 1 }, reflectivity: { value: 1.0 }, refractionRatio: { value: 0.98 }, maxMipLevel: { value: 0 } }, aomap: { aoMap: { value: null }, aoMapIntensity: { value: 1 } }, lightmap: { lightMap: { value: null }, lightMapIntensity: { value: 1 } }, emissivemap: { emissiveMap: { value: null } }, bumpmap: { bumpMap: { value: null }, bumpScale: { value: 1 } }, normalmap: { normalMap: { value: null }, normalScale: { value: new Vector2( 1, 1 ) } }, displacementmap: { displacementMap: { value: null }, displacementScale: { value: 1 }, displacementBias: { value: 0 } }, roughnessmap: { roughnessMap: { value: null } }, metalnessmap: { metalnessMap: { value: null } }, gradientmap: { gradientMap: { value: null } }, fog: { fogDensity: { value: 0.00025 }, fogNear: { value: 1 }, fogFar: { value: 2000 }, fogColor: { value: new Color( 0xffffff ) } }, lights: { ambientLightColor: { value: [] }, lightProbe: { value: [] }, directionalLights: { value: [], properties: { direction: {}, color: {}, shadow: {}, shadowBias: {}, shadowRadius: {}, shadowMapSize: {} } }, directionalShadowMap: { value: [] }, directionalShadowMatrix: { value: [] }, spotLights: { value: [], properties: { color: {}, position: {}, direction: {}, distance: {}, coneCos: {}, penumbraCos: {}, decay: {}, shadow: {}, shadowBias: {}, shadowRadius: {}, shadowMapSize: {} } }, spotShadowMap: { value: [] }, spotShadowMatrix: { value: [] }, pointLights: { value: [], properties: { color: {}, position: {}, decay: {}, distance: {}, shadow: {}, shadowBias: {}, shadowRadius: {}, shadowMapSize: {}, shadowCameraNear: {}, shadowCameraFar: {} } }, pointShadowMap: { value: [] }, pointShadowMatrix: { value: [] }, hemisphereLights: { value: [], properties: { direction: {}, skyColor: {}, groundColor: {} } }, // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src rectAreaLights: { value: [], properties: { color: {}, position: {}, width: {}, height: {} } } }, points: { diffuse: { value: new Color( 0xeeeeee ) }, opacity: { value: 1.0 }, size: { value: 1.0 }, scale: { value: 1.0 }, map: { value: null }, alphaMap: { value: null }, uvTransform: { value: new Matrix3() } }, sprite: { diffuse: { value: new Color( 0xeeeeee ) }, opacity: { value: 1.0 }, center: { value: new Vector2( 0.5, 0.5 ) }, rotation: { value: 0.0 }, map: { value: null }, alphaMap: { value: null }, uvTransform: { value: new Matrix3() } } }; /** * @author mrdoob / http://mrdoob.com/ */ function WebGLAnimation() { var context = null; var isAnimating = false; var animationLoop = null; function onAnimationFrame( time, frame ) { if ( isAnimating === false ) { return; } animationLoop( time, frame ); context.requestAnimationFrame( onAnimationFrame ); } return { start: function () { if ( isAnimating === true ) { return; } if ( animationLoop === null ) { return; } context.requestAnimationFrame( onAnimationFrame ); isAnimating = true; }, stop: function () { isAnimating = false; }, setAnimationLoop: function ( callback ) { animationLoop = callback; }, setContext: function ( value ) { context = value; } }; } /** * @author mrdoob / http://mrdoob.com/ */ function WebGLAttributes( gl, capabilities ) { var isWebGL2 = capabilities.isWebGL2; var buffers = new WeakMap(); function createBuffer( attribute, bufferType ) { var array = attribute.array; var usage = attribute.usage; var buffer = gl.createBuffer(); gl.bindBuffer( bufferType, buffer ); gl.bufferData( bufferType, array, usage ); attribute.onUploadCallback(); var type = 5126; if ( array instanceof Float32Array ) { type = 5126; } else if ( array instanceof Float64Array ) { console.warn( 'THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.' ); } else if ( array instanceof Uint16Array ) { type = 5123; } else if ( array instanceof Int16Array ) { type = 5122; } else if ( array instanceof Uint32Array ) { type = 5125; } else if ( array instanceof Int32Array ) { type = 5124; } else if ( array instanceof Int8Array ) { type = 5120; } else if ( array instanceof Uint8Array ) { type = 5121; } return { buffer: buffer, type: type, bytesPerElement: array.BYTES_PER_ELEMENT, version: attribute.version }; } function updateBuffer( buffer, attribute, bufferType ) { var array = attribute.array; var updateRange = attribute.updateRange; gl.bindBuffer( bufferType, buffer ); if ( updateRange.count === - 1 ) { // Not using update ranges gl.bufferSubData( bufferType, 0, array ); } else { if ( isWebGL2 ) { gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array, updateRange.offset, updateRange.count ); } else { gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array.subarray( updateRange.offset, updateRange.offset + updateRange.count ) ); } updateRange.count = - 1; // reset range } } // function get( attribute ) { if ( attribute.isInterleavedBufferAttribute ) { attribute = attribute.data; } return buffers.get( attribute ); } function remove( attribute ) { if ( attribute.isInterleavedBufferAttribute ) { attribute = attribute.data; } var data = buffers.get( attribute ); if ( data ) { gl.deleteBuffer( data.buffer ); buffers.delete( attribute ); } } function update( attribute, bufferType ) { if ( attribute.isInterleavedBufferAttribute ) { attribute = attribute.data; } var data = buffers.get( attribute ); if ( data === undefined ) { buffers.set( attribute, createBuffer( attribute, bufferType ) ); } else if ( data.version < attribute.version ) { updateBuffer( data.buffer, attribute, bufferType ); data.version = attribute.version; } } return { get: get, remove: remove, update: update }; } /** * @author mrdoob / http://mrdoob.com/ * @author Mugen87 / https://github.com/Mugen87 */ // PlaneGeometry function PlaneGeometry( width, height, widthSegments, heightSegments ) { Geometry.call( this ); this.type = 'PlaneGeometry'; this.parameters = { width: width, height: height, widthSegments: widthSegments, heightSegments: heightSegments }; this.fromBufferGeometry( new PlaneBufferGeometry( width, height, widthSegments, heightSegments ) ); this.mergeVertices(); } PlaneGeometry.prototype = Object.create( Geometry.prototype ); PlaneGeometry.prototype.constructor = PlaneGeometry; // PlaneBufferGeometry function PlaneBufferGeometry( width, height, widthSegments, heightSegments ) { BufferGeometry.call( this ); this.type = 'PlaneBufferGeometry'; this.parameters = { width: width, height: height, widthSegments: widthSegments, heightSegments: heightSegments }; width = width || 1; height = height || 1; var width_half = width / 2; var height_half = height / 2; var gridX = Math.floor( widthSegments ) || 1; var gridY = Math.floor( heightSegments ) || 1; var gridX1 = gridX + 1; var gridY1 = gridY + 1; var segment_width = width / gridX; var segment_height = height / gridY; var ix, iy; // buffers var indices = []; var vertices = []; var normals = []; var uvs = []; // generate vertices, normals and uvs for ( iy = 0; iy < gridY1; iy ++ ) { var y = iy * segment_height - height_half; for ( ix = 0; ix < gridX1; ix ++ ) { var x = ix * segment_width - width_half; vertices.push( x, - y, 0 ); normals.push( 0, 0, 1 ); uvs.push( ix / gridX ); uvs.push( 1 - ( iy / gridY ) ); } } // indices for ( iy = 0; iy < gridY; iy ++ ) { for ( ix = 0; ix < gridX; ix ++ ) { var a = ix + gridX1 * iy; var b = ix + gridX1 * ( iy + 1 ); var c = ( ix + 1 ) + gridX1 * ( iy + 1 ); var d = ( ix + 1 ) + gridX1 * iy; // faces indices.push( a, b, d ); indices.push( b, c, d ); } } // build geometry this.setIndex( indices ); this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); } PlaneBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); PlaneBufferGeometry.prototype.constructor = PlaneBufferGeometry; var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif"; var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif"; var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif"; var aomap_fragment = "#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_ENVMAP ) && defined( STANDARD )\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.specularRoughness );\n\t#endif\n#endif"; var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif"; var begin_vertex = "vec3 transformed = vec3( position );"; var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif"; var bsdfs = "vec2 integrateSpecularBRDF( const in float dotNV, const in float roughness ) {\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\treturn vec2( -1.04, 1.04 ) * a004 + r.zw;\n}\nfloat punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\tif( cutoffDistance > 0.0 ) {\n\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t}\n\treturn distanceFalloff;\n#else\n\tif( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\t}\n\treturn 1.0;\n#endif\n}\nvec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 specularColor, const in float dotLH ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );\n\treturn ( 1.0 - specularColor ) * fresnel + specularColor;\n}\nvec3 F_Schlick_RoughnessDependent( const in vec3 F0, const in float dotNV, const in float roughness ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotNV - 6.98316 ) * dotNV );\n\tvec3 Fr = max( vec3( 1.0 - roughness ), F0 ) - F0;\n\treturn Fr * fresnel + F0;\n}\nfloat G_GGX_Smith( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\tfloat gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\treturn 1.0 / ( gl * gv );\n}\nfloat G_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_Specular_GGX( const in IncidentLight incidentLight, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( incidentLight.direction + viewDir );\n\tfloat dotNL = saturate( dot( normal, incidentLight.direction ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( G * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\nvec3 BRDF_Specular_GGX_Environment( const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tvec2 brdf = integrateSpecularBRDF( dotNV, roughness );\n\treturn specularColor * brdf.x + brdf.y;\n}\nvoid BRDF_Specular_Multiscattering_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tvec3 F = F_Schlick_RoughnessDependent( specularColor, dotNV, roughness );\n\tvec2 brdf = integrateSpecularBRDF( dotNV, roughness );\n\tvec3 FssEss = F * brdf.x + brdf.y;\n\tfloat Ess = brdf.x + brdf.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = specularColor + ( 1.0 - specularColor ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_Specular_BlinnPhong( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\nfloat GGXRoughnessToBlinnExponent( const in float ggxRoughness ) {\n\treturn ( 2.0 / pow2( ggxRoughness + 0.0001 ) - 2.0 );\n}\nfloat BlinnExponentToGGXRoughness( const in float blinnExponent ) {\n\treturn sqrt( 2.0 / ( blinnExponent + 2.0 ) );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie(float roughness, float NoH) {\n\tfloat invAlpha = 1.0 / roughness;\n\tfloat cos2h = NoH * NoH;\n\tfloat sin2h = max(1.0 - cos2h, 0.0078125);\treturn (2.0 + invAlpha) * pow(sin2h, invAlpha * 0.5) / (2.0 * PI);\n}\nfloat V_Neubelt(float NoV, float NoL) {\n\treturn saturate(1.0 / (4.0 * (NoL + NoV - NoL * NoV)));\n}\nvec3 BRDF_Specular_Sheen( const in float roughness, const in vec3 L, const in GeometricContext geometry, vec3 specularColor ) {\n\tvec3 N = geometry.normal;\n\tvec3 V = geometry.viewDir;\n\tvec3 H = normalize( V + L );\n\tfloat dotNH = saturate( dot( N, H ) );\n\treturn specularColor * D_Charlie( roughness, dotNH ) * V_Neubelt( dot(N, V), dot(N, L) );\n}\n#endif"; var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vUv );\n\t\tvec2 dSTdy = dFdy( vUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {\n\t\tvec3 vSigmaX = vec3( dFdx( surf_pos.x ), dFdx( surf_pos.y ), dFdx( surf_pos.z ) );\n\t\tvec3 vSigmaY = vec3( dFdy( surf_pos.x ), dFdy( surf_pos.y ), dFdy( surf_pos.z ) );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 );\n\t\tfDet *= ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif"; var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvec4 plane;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\tplane = clippingPlanes[ i ];\n\t\tif ( dot( vViewPosition, plane.xyz ) > plane.w ) discard;\n\t}\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\tbool clipped = true;\n\t\t#pragma unroll_loop\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vViewPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t}\n\t\tif ( clipped ) discard;\n\t#endif\n#endif"; var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\t#if ! defined( STANDARD ) && ! defined( PHONG ) && ! defined( MATCAP )\n\t\tvarying vec3 vViewPosition;\n\t#endif\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif"; var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( STANDARD ) && ! defined( PHONG ) && ! defined( MATCAP )\n\tvarying vec3 vViewPosition;\n#endif"; var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( STANDARD ) && ! defined( PHONG ) && ! defined( MATCAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif"; var color_fragment = "#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif"; var color_pars_fragment = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif"; var color_pars_vertex = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif"; var color_vertex = "#ifdef USE_COLOR\n\tvColor.xyz = color.xyz;\n#endif"; var common = "#define PI 3.14159265359\n#define PI2 6.28318530718\n#define PI_HALF 1.5707963267949\n#define RECIPROCAL_PI 0.31830988618\n#define RECIPROCAL_PI2 0.15915494\n#define LOG2 1.442695\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement(a) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract(sin(sn) * c);\n}\n#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat max3( vec3 v ) { return max( max( v.x, v.y ), v.z ); }\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n#ifdef CLEARCOAT\n\tvec3 clearcoatNormal;\n#endif\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nvec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\tfloat distance = dot( planeNormal, point - pointOnPlane );\n\treturn - distance * planeNormal + point;\n}\nfloat sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn sign( dot( point - pointOnPlane, planeNormal ) );\n}\nvec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) ) + pointOnLine;\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nfloat linearToRelativeLuminance( const in vec3 color ) {\n\tvec3 weights = vec3( 0.2126, 0.7152, 0.0722 );\n\treturn dot( weights, color.rgb );\n}\nbool isPerspectiveMatrix( mat4 m ) {\n return m[ 2 ][ 3 ] == - 1.0;\n}"; var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n#define cubeUV_maxMipLevel 8.0\n#define cubeUV_minMipLevel 4.0\n#define cubeUV_maxTileSize 256.0\n#define cubeUV_minTileSize 16.0\nfloat getFace(vec3 direction) {\n vec3 absDirection = abs(direction);\n float face = -1.0;\n if (absDirection.x > absDirection.z) {\n if (absDirection.x > absDirection.y)\n face = direction.x > 0.0 ? 0.0 : 3.0;\n else\n face = direction.y > 0.0 ? 1.0 : 4.0;\n } else {\n if (absDirection.z > absDirection.y)\n face = direction.z > 0.0 ? 2.0 : 5.0;\n else\n face = direction.y > 0.0 ? 1.0 : 4.0;\n }\n return face;\n}\nvec2 getUV(vec3 direction, float face) {\n vec2 uv;\n if (face == 0.0) {\n uv = vec2(-direction.z, direction.y) / abs(direction.x);\n } else if (face == 1.0) {\n uv = vec2(direction.x, -direction.z) / abs(direction.y);\n } else if (face == 2.0) {\n uv = direction.xy / abs(direction.z);\n } else if (face == 3.0) {\n uv = vec2(direction.z, direction.y) / abs(direction.x);\n } else if (face == 4.0) {\n uv = direction.xz / abs(direction.y);\n } else {\n uv = vec2(-direction.x, direction.y) / abs(direction.z);\n }\n return 0.5 * (uv + 1.0);\n}\nvec3 bilinearCubeUV(sampler2D envMap, vec3 direction, float mipInt) {\n float face = getFace(direction);\n float filterInt = max(cubeUV_minMipLevel - mipInt, 0.0);\n mipInt = max(mipInt, cubeUV_minMipLevel);\n float faceSize = exp2(mipInt);\n float texelSize = 1.0 / (3.0 * cubeUV_maxTileSize);\n vec2 uv = getUV(direction, face) * (faceSize - 1.0);\n vec2 f = fract(uv);\n uv += 0.5 - f;\n if (face > 2.0) {\n uv.y += faceSize;\n face -= 3.0;\n }\n uv.x += face * faceSize;\n if(mipInt < cubeUV_maxMipLevel){\n uv.y += 2.0 * cubeUV_maxTileSize;\n }\n uv.y += filterInt * 2.0 * cubeUV_minTileSize;\n uv.x += 3.0 * max(0.0, cubeUV_maxTileSize - 2.0 * faceSize);\n uv *= texelSize;\n vec3 tl = envMapTexelToLinear(texture2D(envMap, uv)).rgb;\n uv.x += texelSize;\n vec3 tr = envMapTexelToLinear(texture2D(envMap, uv)).rgb;\n uv.y += texelSize;\n vec3 br = envMapTexelToLinear(texture2D(envMap, uv)).rgb;\n uv.x -= texelSize;\n vec3 bl = envMapTexelToLinear(texture2D(envMap, uv)).rgb;\n vec3 tm = mix(tl, tr, f.x);\n vec3 bm = mix(bl, br, f.x);\n return mix(tm, bm, f.y);\n}\n#define r0 1.0\n#define v0 0.339\n#define m0 -2.0\n#define r1 0.8\n#define v1 0.276\n#define m1 -1.0\n#define r4 0.4\n#define v4 0.046\n#define m4 2.0\n#define r5 0.305\n#define v5 0.016\n#define m5 3.0\n#define r6 0.21\n#define v6 0.0038\n#define m6 4.0\nfloat roughnessToMip(float roughness) {\n float mip = 0.0;\n if (roughness >= r1) {\n mip = (r0 - roughness) * (m1 - m0) / (r0 - r1) + m0;\n } else if (roughness >= r4) {\n mip = (r1 - roughness) * (m4 - m1) / (r1 - r4) + m1;\n } else if (roughness >= r5) {\n mip = (r4 - roughness) * (m5 - m4) / (r4 - r5) + m4;\n } else if (roughness >= r6) {\n mip = (r5 - roughness) * (m6 - m5) / (r5 - r6) + m5;\n } else {\n mip = -2.0 * log2(1.16 * roughness); }\n return mip;\n}\nvec4 textureCubeUV(sampler2D envMap, vec3 sampleDir, float roughness) {\n float mip = clamp(roughnessToMip(roughness), m0, cubeUV_maxMipLevel);\n float mipF = fract(mip);\n float mipInt = floor(mip);\n vec3 color0 = bilinearCubeUV(envMap, sampleDir, mipInt);\n if (mipF == 0.0) {\n return vec4(color0, 1.0);\n } else {\n vec3 color1 = bilinearCubeUV(envMap, sampleDir, mipInt + 1.0);\n return vec4(mix(color0, color1, mipF), 1.0);\n }\n}\n#endif"; var defaultnormal_vertex = "vec3 transformedNormal = objectNormal;\n#ifdef USE_INSTANCING\n\ttransformedNormal = mat3( instanceMatrix ) * transformedNormal;\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n\tvec3 transformedTangent = ( modelViewMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#ifdef FLIP_SIDED\n\t\ttransformedTangent = - transformedTangent;\n\t#endif\n#endif"; var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif"; var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif"; var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif"; var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif"; var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );"; var encodings_pars_fragment = "\nvec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 GammaToLinear( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.rgb, vec3( gammaFactor ) ), value.a );\n}\nvec4 LinearToGamma( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.rgb, vec3( 1.0 / gammaFactor ) ), value.a );\n}\nvec4 sRGBToLinear( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );\n}\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );\n}\nvec4 RGBEToLinear( in vec4 value ) {\n\treturn vec4( value.rgb * exp2( value.a * 255.0 - 128.0 ), 1.0 );\n}\nvec4 LinearToRGBE( in vec4 value ) {\n\tfloat maxComponent = max( max( value.r, value.g ), value.b );\n\tfloat fExp = clamp( ceil( log2( maxComponent ) ), -128.0, 127.0 );\n\treturn vec4( value.rgb / exp2( fExp ), ( fExp + 128.0 ) / 255.0 );\n}\nvec4 RGBMToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * value.a * maxRange, 1.0 );\n}\nvec4 LinearToRGBM( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.r, max( value.g, value.b ) );\n\tfloat M = clamp( maxRGB / maxRange, 0.0, 1.0 );\n\tM = ceil( M * 255.0 ) / 255.0;\n\treturn vec4( value.rgb / ( M * maxRange ), M );\n}\nvec4 RGBDToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * ( ( maxRange / 255.0 ) / value.a ), 1.0 );\n}\nvec4 LinearToRGBD( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.r, max( value.g, value.b ) );\n\tfloat D = max( maxRange / maxRGB, 1.0 );\n\tD = clamp( floor( D ) / 255.0, 0.0, 1.0 );\n\treturn vec4( value.rgb * ( D * ( 255.0 / maxRange ) ), D );\n}\nconst mat3 cLogLuvM = mat3( 0.2209, 0.3390, 0.4184, 0.1138, 0.6780, 0.7319, 0.0102, 0.1130, 0.2969 );\nvec4 LinearToLogLuv( in vec4 value ) {\n\tvec3 Xp_Y_XYZp = cLogLuvM * value.rgb;\n\tXp_Y_XYZp = max( Xp_Y_XYZp, vec3( 1e-6, 1e-6, 1e-6 ) );\n\tvec4 vResult;\n\tvResult.xy = Xp_Y_XYZp.xy / Xp_Y_XYZp.z;\n\tfloat Le = 2.0 * log2(Xp_Y_XYZp.y) + 127.0;\n\tvResult.w = fract( Le );\n\tvResult.z = ( Le - ( floor( vResult.w * 255.0 ) ) / 255.0 ) / 255.0;\n\treturn vResult;\n}\nconst mat3 cLogLuvInverseM = mat3( 6.0014, -2.7008, -1.7996, -1.3320, 3.1029, -5.7721, 0.3008, -1.0882, 5.6268 );\nvec4 LogLuvToLinear( in vec4 value ) {\n\tfloat Le = value.z * 255.0 + value.w;\n\tvec3 Xp_Y_XYZp;\n\tXp_Y_XYZp.y = exp2( ( Le - 127.0 ) / 2.0 );\n\tXp_Y_XYZp.z = Xp_Y_XYZp.y / value.y;\n\tXp_Y_XYZp.x = value.x * Xp_Y_XYZp.z;\n\tvec3 vRGB = cLogLuvInverseM * Xp_Y_XYZp.rgb;\n\treturn vec4( max( vRGB, 0.0 ), 1.0 );\n}"; var envmap_fragment = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\t\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 envColor = textureCubeUV( envMap, reflectVec, 0.0 );\n\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\tvec2 sampleUV;\n\t\treflectVec = normalize( reflectVec );\n\t\tsampleUV.y = asin( clamp( reflectVec.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\t\tsampleUV.x = atan( reflectVec.z, reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\tvec4 envColor = texture2D( envMap, sampleUV );\n\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\treflectVec = normalize( reflectVec );\n\t\tvec3 reflectView = normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0, 0.0, 1.0 ) );\n\t\tvec4 envColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5 );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\t#ifndef ENVMAP_TYPE_CUBE_UV\n\t\tenvColor = envMapTexelToLinear( envColor );\n\t#endif\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif"; var envmap_common_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\n\tuniform int maxMipLevel;\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\t\n#endif"; var envmap_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float reflectivity;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\tvarying vec3 vWorldPosition;\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif"; var envmap_pars_vertex = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) ||defined( PHONG )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\t\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif"; var envmap_vertex = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex;\n\t\tif ( isOrthographic ) { \n\t\t\tcameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif"; var fog_vertex = "#ifdef USE_FOG\n\tfogDepth = -mvPosition.z;\n#endif"; var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float fogDepth;\n#endif"; var fog_fragment = "#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * fogDepth * fogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, fogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif"; var fog_pars_fragment = "#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float fogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif"; var gradientmap_pars_fragment = "#ifdef USE_GRADIENTMAP\n\tuniform sampler2D gradientMap;\n#endif\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\tfloat dotNL = dot( normal, lightDirection );\n\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t#ifdef USE_GRADIENTMAP\n\t\treturn texture2D( gradientMap, coord ).rgb;\n\t#else\n\t\treturn ( coord.x < 0.7 ) ? vec3( 0.7 ) : vec3( 1.0 );\n\t#endif\n}"; var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\treflectedLight.indirectDiffuse += PI * lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n#endif"; var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif"; var lights_lambert_vertex = "vec3 diffuse = vec3( 1.0 );\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( -mvPosition.xyz );\nGeometricContext backGeometry;\nbackGeometry.position = geometry.position;\nbackGeometry.normal = -geometry.normal;\nbackGeometry.viewDir = geometry.viewDir;\nvLightFront = vec3( 0.0 );\nvIndirectFront = vec3( 0.0 );\n#ifdef DOUBLE_SIDED\n\tvLightBack = vec3( 0.0 );\n\tvIndirectBack = vec3( 0.0 );\n#endif\nIncidentLight directLight;\nfloat dotNL;\nvec3 directLightColor_Diffuse;\n#if NUM_POINT_LIGHTS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tgetPointDirectLightIrradiance( pointLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tgetSpotDirectLightIrradiance( spotLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_DIR_LIGHTS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tgetDirectionalDirectLightIrradiance( directionalLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\tvIndirectFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvIndirectBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\n\t\t#endif\n\t}\n#endif"; var lights_pars_begin = "uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\nuniform vec3 lightProbe[ 9 ];\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in GeometricContext geometry ) {\n\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treturn irradiance;\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalDirectLightIrradiance( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tdirectLight.color = directionalLight.color;\n\t\tdirectLight.direction = directionalLight.direction;\n\t\tdirectLight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t\tfloat shadowCameraNear;\n\t\tfloat shadowCameraFar;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointDirectLightIrradiance( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tdirectLight.color = pointLight.color;\n\t\tdirectLight.color *= punctualLightIntensityToIrradianceFactor( lightDistance, pointLight.distance, pointLight.decay );\n\t\tdirectLight.visible = ( directLight.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotDirectLightIrradiance( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tfloat angleCos = dot( directLight.direction, spotLight.direction );\n\t\tif ( angleCos > spotLight.coneCos ) {\n\t\t\tfloat spotEffect = smoothstep( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\t\tdirectLight.color = spotLight.color;\n\t\t\tdirectLight.color *= spotEffect * punctualLightIntensityToIrradianceFactor( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tdirectLight.visible = true;\n\t\t} else {\n\t\t\tdirectLight.color = vec3( 0.0 );\n\t\t\tdirectLight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in GeometricContext geometry ) {\n\t\tfloat dotNL = dot( geometry.normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tirradiance *= PI;\n\t\t#endif\n\t\treturn irradiance;\n\t}\n#endif"; var envmap_physical_pars_fragment = "#if defined( USE_ENVMAP )\n\t#ifdef ENVMAP_MODE_REFRACTION\n\t\tuniform float refractionRatio;\n\t#endif\n\tvec3 getLightProbeIndirectIrradiance( const in GeometricContext geometry, const in int maxMIPLevel ) {\n\t\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 );\n\t\t#else\n\t\t\tvec4 envMapColor = vec4( 0.0 );\n\t\t#endif\n\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t}\n\tfloat getSpecularMIPLevel( const in float roughness, const in int maxMIPLevel ) {\n\t\tfloat maxMIPLevelScalar = float( maxMIPLevel );\n\t\tfloat sigma = PI * roughness * roughness / ( 1.0 + roughness );\n\t\tfloat desiredMIPLevel = maxMIPLevelScalar + log2( sigma );\n\t\treturn clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );\n\t}\n\tvec3 getLightProbeIndirectRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in int maxMIPLevel ) {\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t vec3 reflectVec = reflect( -viewDir, normal );\n\t\t reflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t#else\n\t\t vec3 reflectVec = refract( -viewDir, normal, refractionRatio );\n\t\t#endif\n\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\tfloat specularMIPLevel = getSpecularMIPLevel( roughness, maxMIPLevel );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness );\n\t\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\t\tvec2 sampleUV;\n\t\t\tsampleUV.y = asin( clamp( reflectVec.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\t\t\tsampleUV.x = atan( reflectVec.z, reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, sampleUV, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = texture2D( envMap, sampleUV, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\t\tvec3 reflectView = normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0,0.0,1.0 ) );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#endif\n\t\treturn envMapColor.rgb * envMapIntensity;\n\t}\n#endif"; var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;"; var lights_toon_pars_fragment = "varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct ToonMaterial {\n\tvec3\tdiffuseColor;\n\tvec3\tspecularColor;\n\tfloat\tspecularShininess;\n\tfloat\tspecularStrength;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon\n#define Material_LightProbeLOD( material )\t(0)"; var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;"; var lights_phong_pars_fragment = "varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct BlinnPhongMaterial {\n\tvec3\tdiffuseColor;\n\tvec3\tspecularColor;\n\tfloat\tspecularShininess;\n\tfloat\tspecularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)"; var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.specularRoughness = max( roughnessFactor, 0.0525 );material.specularRoughness += geometryRoughness;\nmaterial.specularRoughness = min( material.specularRoughness, 1.0 );\n#ifdef REFLECTIVITY\n\tmaterial.specularColor = mix( vec3( MAXIMUM_SPECULAR_COEFFICIENT * pow2( reflectivity ) ), diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( DEFAULT_SPECULAR_COEFFICIENT ), diffuseColor.rgb, metalnessFactor );\n#endif\n#ifdef CLEARCOAT\n\tmaterial.clearcoat = saturate( clearcoat );\tmaterial.clearcoatRoughness = max( clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheen;\n#endif"; var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3\tdiffuseColor;\n\tfloat\tspecularRoughness;\n\tvec3\tspecularColor;\n#ifdef CLEARCOAT\n\tfloat clearcoat;\n\tfloat clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tvec3 sheenColor;\n#endif\n};\n#define MAXIMUM_SPECULAR_COEFFICIENT 0.16\n#define DEFAULT_SPECULAR_COEFFICIENT 0.04\nfloat clearcoatDHRApprox( const in float roughness, const in float dotNL ) {\n\treturn DEFAULT_SPECULAR_COEFFICIENT + ( 1.0 - DEFAULT_SPECULAR_COEFFICIENT ) * ( pow( 1.0 - dotNL, 5.0 ) * pow( 1.0 - roughness, 2.0 ) );\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.specularRoughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\t#ifdef CLEARCOAT\n\t\tfloat ccDotNL = saturate( dot( geometry.clearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = ccDotNL * directLight.color;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tccIrradiance *= PI;\n\t\t#endif\n\t\tfloat clearcoatDHR = material.clearcoat * clearcoatDHRApprox( material.clearcoatRoughness, ccDotNL );\n\t\treflectedLight.directSpecular += ccIrradiance * material.clearcoat * BRDF_Specular_GGX( directLight, geometry.viewDir, geometry.clearcoatNormal, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearcoatRoughness );\n\t#else\n\t\tfloat clearcoatDHR = 0.0;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\treflectedLight.directSpecular += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Specular_Sheen(\n\t\t\tmaterial.specularRoughness,\n\t\t\tdirectLight.direction,\n\t\t\tgeometry,\n\t\t\tmaterial.sheenColor\n\t\t);\n\t#else\n\t\treflectedLight.directSpecular += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Specular_GGX( directLight, geometry.viewDir, geometry.normal, material.specularColor, material.specularRoughness);\n\t#endif\n\treflectedLight.directDiffuse += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef CLEARCOAT\n\t\tfloat ccDotNV = saturate( dot( geometry.clearcoatNormal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular += clearcoatRadiance * material.clearcoat * BRDF_Specular_GGX_Environment( geometry.viewDir, geometry.clearcoatNormal, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearcoatRoughness );\n\t\tfloat ccDotNL = ccDotNV;\n\t\tfloat clearcoatDHR = material.clearcoat * clearcoatDHRApprox( material.clearcoatRoughness, ccDotNL );\n\t#else\n\t\tfloat clearcoatDHR = 0.0;\n\t#endif\n\tfloat clearcoatInv = 1.0 - clearcoatDHR;\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\tBRDF_Specular_Multiscattering_Environment( geometry, material.specularColor, material.specularRoughness, singleScattering, multiScattering );\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - ( singleScattering + multiScattering ) );\n\treflectedLight.indirectSpecular += clearcoatInv * radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}"; var lights_fragment_begin = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n#ifdef CLEARCOAT\n\tgeometry.clearcoatNormal = clearcoatNormal;\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointDirectLightIrradiance( pointLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tdirectLight.color *= all( bvec3( pointLight.shadow, directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotDirectLightIrradiance( spotLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tdirectLight.color *= all( bvec3( spotLight.shadow, directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalDirectLightIrradiance( directionalLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectLight.color *= all( bvec3( directionalLight.shadow, directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\tirradiance += getLightProbeIrradiance( lightProbe, geometry );\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t}\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif"; var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\t\tvec3 lightMapIrradiance = lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tlightMapIrradiance *= PI;\n\t\t#endif\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getLightProbeIndirectIrradiance( geometry, maxMipLevel );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tradiance += getLightProbeIndirectRadiance( geometry.viewDir, geometry.normal, material.specularRoughness, maxMipLevel );\n\t#ifdef CLEARCOAT\n\t\tclearcoatRadiance += getLightProbeIndirectRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness, maxMipLevel );\n\t#endif\n#endif"; var lights_fragment_end = "#if defined( RE_IndirectDiffuse )\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n\tRE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometry, material, reflectedLight );\n#endif"; var logdepthbuf_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tgl_FragDepthEXT = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif"; var logdepthbuf_pars_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif"; var logdepthbuf_pars_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t\tvarying float vIsPerspective;\n\t#else\n\t\tuniform float logDepthBufFC;\n\t#endif\n#endif"; var logdepthbuf_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n\t#else\n\t\tif ( isPerspectiveMatrix( projectionMatrix ) ) {\n\t\t\tgl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0;\n\t\t\tgl_Position.z *= gl_Position.w;\n\t\t}\n\t#endif\n#endif"; var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif"; var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif"; var map_particle_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n#endif\n#ifdef USE_MAP\n\tvec4 mapTexel = texture2D( map, uv );\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif"; var map_particle_pars_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tuniform mat3 uvTransform;\n#endif\n#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif"; var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif"; var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif"; var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\tobjectNormal += morphNormal0 * morphTargetInfluences[ 0 ];\n\tobjectNormal += morphNormal1 * morphTargetInfluences[ 1 ];\n\tobjectNormal += morphNormal2 * morphTargetInfluences[ 2 ];\n\tobjectNormal += morphNormal3 * morphTargetInfluences[ 3 ];\n#endif"; var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\tuniform float morphTargetBaseInfluence;\n\t#ifndef USE_MORPHNORMALS\n\tuniform float morphTargetInfluences[ 8 ];\n\t#else\n\tuniform float morphTargetInfluences[ 4 ];\n\t#endif\n#endif"; var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\ttransformed += morphTarget0 * morphTargetInfluences[ 0 ];\n\ttransformed += morphTarget1 * morphTargetInfluences[ 1 ];\n\ttransformed += morphTarget2 * morphTargetInfluences[ 2 ];\n\ttransformed += morphTarget3 * morphTargetInfluences[ 3 ];\n\t#ifndef USE_MORPHNORMALS\n\ttransformed += morphTarget4 * morphTargetInfluences[ 4 ];\n\ttransformed += morphTarget5 * morphTargetInfluences[ 5 ];\n\ttransformed += morphTarget6 * morphTargetInfluences[ 6 ];\n\ttransformed += morphTarget7 * morphTargetInfluences[ 7 ];\n\t#endif\n#endif"; var normal_fragment_begin = "#ifdef FLAT_SHADED\n\tvec3 fdx = vec3( dFdx( vViewPosition.x ), dFdx( vViewPosition.y ), dFdx( vViewPosition.z ) );\n\tvec3 fdy = vec3( dFdy( vViewPosition.x ), dFdy( vViewPosition.y ), dFdy( vViewPosition.z ) );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t#endif\n\t#ifdef USE_TANGENT\n\t\tvec3 tangent = normalize( vTangent );\n\t\tvec3 bitangent = normalize( vBitangent );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\ttangent = tangent * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\t\tbitangent = bitangent * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\t#endif\n\t\t#if defined( TANGENTSPACE_NORMALMAP ) || defined( USE_CLEARCOAT_NORMALMAP )\n\t\t\tmat3 vTBN = mat3( tangent, bitangent, normal );\n\t\t#endif\n\t#endif\n#endif\nvec3 geometryNormal = normal;"; var normal_fragment_maps = "#ifdef OBJECTSPACE_NORMALMAP\n\tnormal = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t#ifdef FLIP_SIDED\n\t\tnormal = - normal;\n\t#endif\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t#endif\n\tnormal = normalize( normalMatrix * normal );\n#elif defined( TANGENTSPACE_NORMALMAP )\n\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\tmapN.xy *= normalScale;\n\t#ifdef USE_TANGENT\n\t\tnormal = normalize( vTBN * mapN );\n\t#else\n\t\tnormal = perturbNormal2Arb( -vViewPosition, normal, mapN );\n\t#endif\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n#endif"; var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\n\tuniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( TANGENTSPACE_NORMALMAP ) || defined ( USE_CLEARCOAT_NORMALMAP ) )\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec3 mapN ) {\n\t\tvec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );\n\t\tvec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );\n\t\tvec2 st0 = dFdx( vUv.st );\n\t\tvec2 st1 = dFdy( vUv.st );\n\t\tfloat scale = sign( st1.t * st0.s - st0.t * st1.s );\n\t\tvec3 S = normalize( ( q0 * st1.t - q1 * st0.t ) * scale );\n\t\tvec3 T = normalize( ( - q0 * st1.s + q1 * st0.s ) * scale );\n\t\tvec3 N = normalize( surf_norm );\n\t\tmat3 tsn = mat3( S, T, N );\n\t\tmapN.xy *= ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\treturn normalize( tsn * mapN );\n\t}\n#endif"; var clearcoat_normal_fragment_begin = "#ifdef CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif"; var clearcoat_normal_fragment_maps = "#ifdef USE_CLEARCOAT_NORMALMAP\n\tvec3 clearcoatMapN = texture2D( clearcoatNormalMap, vUv ).xyz * 2.0 - 1.0;\n\tclearcoatMapN.xy *= clearcoatNormalScale;\n\t#ifdef USE_TANGENT\n\t\tclearcoatNormal = normalize( vTBN * clearcoatMapN );\n\t#else\n\t\tclearcoatNormal = perturbNormal2Arb( - vViewPosition, clearcoatNormal, clearcoatMapN );\n\t#endif\n#endif"; var clearcoat_normalmap_pars_fragment = "#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif"; var packing = "vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nvec4 pack2HalfToRGBA( vec2 v ) {\n\tvec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ));\n\treturn vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w);\n}\nvec2 unpackRGBATo2Half( vec4 v ) {\n\treturn vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n\treturn linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn (( near + viewZ ) * far ) / (( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * invClipZ - far );\n}"; var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif"; var project_vertex = "vec4 mvPosition = vec4( transformed, 1.0 );\n#ifdef USE_INSTANCING\n\tmvPosition = instanceMatrix * mvPosition;\n#endif\nmvPosition = modelViewMatrix * mvPosition;\ngl_Position = projectionMatrix * mvPosition;"; var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif"; var dithering_pars_fragment = "#ifdef DITHERING\n\tvec3 dithering( vec3 color ) {\n\t\tfloat grid_position = rand( gl_FragCoord.xy );\n\t\tvec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\n\t\tdither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\n\t\treturn color + dither_shift_RGB;\n\t}\n#endif"; var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif"; var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif"; var shadowmap_pars_fragment = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tvec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n\t\treturn unpackRGBATo2Half( texture2D( shadow, uv ) );\n\t}\n\tfloat VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n\t\tfloat occlusion = 1.0;\n\t\tvec2 distribution = texture2DDistribution( shadow, uv );\n\t\tfloat hard_shadow = step( compare , distribution.x );\n\t\tif (hard_shadow != 1.0 ) {\n\t\t\tfloat distance = compare - distribution.x ;\n\t\t\tfloat variance = max( 0.00000, distribution.y * distribution.y );\n\t\t\tfloat softness_probability = variance / (variance + distance * distance );\t\t\tsoftness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );\t\t\tocclusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n\t\t}\n\t\treturn occlusion;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n\t\tbool inFrustum = all( inFrustumVec );\n\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\t\tbool frustumTest = all( frustumTestVec );\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tfloat dx2 = dx0 / 2.0;\n\t\t\tfloat dy2 = dy0 / 2.0;\n\t\t\tfloat dx3 = dx1 / 2.0;\n\t\t\tfloat dy3 = dy1 / 2.0;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 17.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx = texelSize.x;\n\t\t\tfloat dy = texelSize.y;\n\t\t\tvec2 uv = shadowCoord.xy;\n\t\t\tvec2 f = fract( uv * shadowMapSize + 0.5 );\n\t\t\tuv -= f * texelSize;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, uv, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ), \n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ), \n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t f.y )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\t\tshadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn shadow;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tfloat dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\tdp += shadowBias;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif"; var shadowmap_pars_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n#endif"; var shadowmap_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n#endif"; var shadowmask_pars_fragment = "float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLight directionalLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tshadow *= all( bvec2( directionalLight.shadow, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLight spotLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tshadow *= all( bvec2( spotLight.shadow, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLight pointLight;\n\t#pragma unroll_loop\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tshadow *= all( bvec2( pointLight.shadow, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#endif\n\t#endif\n\treturn shadow;\n}"; var skinbase_vertex = "#ifdef USE_SKINNING\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif"; var skinning_pars_vertex = "#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\t#ifdef BONE_TEXTURE\n\t\tuniform highp sampler2D boneTexture;\n\t\tuniform int boneTextureSize;\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tfloat j = i * 4.0;\n\t\t\tfloat x = mod( j, float( boneTextureSize ) );\n\t\t\tfloat y = floor( j / float( boneTextureSize ) );\n\t\t\tfloat dx = 1.0 / float( boneTextureSize );\n\t\t\tfloat dy = 1.0 / float( boneTextureSize );\n\t\t\ty = dy * ( y + 0.5 );\n\t\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\t\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\t\t\treturn bone;\n\t\t}\n\t#else\n\t\tuniform mat4 boneMatrices[ MAX_BONES ];\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tmat4 bone = boneMatrices[ int(i) ];\n\t\t\treturn bone;\n\t\t}\n\t#endif\n#endif"; var skinning_vertex = "#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\ttransformed = ( bindMatrixInverse * skinned ).xyz;\n#endif"; var skinnormal_vertex = "#ifdef USE_SKINNING\n\tmat4 skinMatrix = mat4( 0.0 );\n\tskinMatrix += skinWeight.x * boneMatX;\n\tskinMatrix += skinWeight.y * boneMatY;\n\tskinMatrix += skinWeight.z * boneMatZ;\n\tskinMatrix += skinWeight.w * boneMatW;\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n\t#ifdef USE_TANGENT\n\t\tobjectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#endif\n#endif"; var specularmap_fragment = "float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif"; var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif"; var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif"; var tonemapping_pars_fragment = "#ifndef saturate\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nuniform float toneMappingWhitePoint;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn toneMappingExposure * color;\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\n#define Uncharted2Helper( x ) max( ( ( x * ( 0.15 * x + 0.10 * 0.50 ) + 0.20 * 0.02 ) / ( x * ( 0.15 * x + 0.50 ) + 0.20 * 0.30 ) ) - 0.02 / 0.30, vec3( 0.0 ) )\nvec3 Uncharted2ToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( Uncharted2Helper( color ) / Uncharted2Helper( vec3( toneMappingWhitePoint ) ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\nvec3 ACESFilmicToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( ( color * ( 2.51 * color + 0.03 ) ) / ( color * ( 2.43 * color + 0.59 ) + 0.14 ) );\n}"; var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif"; var uv_pars_vertex = "#ifdef USE_UV\n\t#ifdef UVS_VERTEX_ONLY\n\t\tvec2 vUv;\n\t#else\n\t\tvarying vec2 vUv;\n\t#endif\n\tuniform mat3 uvTransform;\n#endif"; var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif"; var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif"; var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n\tuniform mat3 uv2Transform;\n#endif"; var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif"; var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP )\n\tvec4 worldPosition = vec4( transformed, 1.0 );\n\t#ifdef USE_INSTANCING\n\t\tworldPosition = instanceMatrix * worldPosition;\n\t#endif\n\tworldPosition = modelMatrix * worldPosition;\n#endif"; var background_frag = "uniform sampler2D t2D;\nvarying vec2 vUv;\nvoid main() {\n\tvec4 texColor = texture2D( t2D, vUv );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\t#include \n\t#include \n}"; var background_vert = "varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\tgl_Position = vec4( position.xy, 1.0, 1.0 );\n}"; var cube_frag = "#include \nuniform float opacity;\nvarying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvec3 vReflect = vWorldDirection;\n\t#include \n\tgl_FragColor = envColor;\n\tgl_FragColor.a *= opacity;\n\t#include \n\t#include \n}"; var cube_vert = "varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n\tgl_Position.z = gl_Position.w;\n}"; var depth_frag = "#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - gl_FragCoord.z ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( gl_FragCoord.z );\n\t#endif\n}"; var depth_vert = "#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; var distanceRGBA_frag = "#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main () {\n\t#include \n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include \n\t#include \n\t#include \n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}"; var distanceRGBA_vert = "#define DISTANCE\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvWorldPosition = worldPosition.xyz;\n}"; var equirect_frag = "uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV;\n\tsampleUV.y = asin( clamp( direction.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\tsampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;\n\tvec4 texColor = texture2D( tEquirect, sampleUV );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\t#include \n\t#include \n}"; var equirect_vert = "varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n}"; var linedashed_frag = "uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n}"; var linedashed_vert = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvLineDistance = scale * lineDistance;\n\tvec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include \n\t#include \n\t#include \n}"; var meshbasic_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\n\t\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\t\treflectedLight.indirectDiffuse += lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include \n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include \n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n}"; var meshbasic_vert = "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#ifdef USE_ENVMAP\n\t#include \n\t#include \n\t#include \n\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; var meshlambert_frag = "uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\treflectedLight.indirectDiffuse = getAmbientLightIrradiance( ambientLightColor );\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.indirectDiffuse += ( gl_FrontFacing ) ? vIndirectFront : vIndirectBack;\n\t#else\n\t\treflectedLight.indirectDiffuse += vIndirectFront;\n\t#endif\n\t#include \n\treflectedLight.indirectDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb );\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\n\t#else\n\t\treflectedLight.directDiffuse = vLightFront;\n\t#endif\n\treflectedLight.directDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb ) * getShadowMask();\n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include \n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; var meshlambert_vert = "#define LAMBERT\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; var meshmatcap_frag = "#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t\tmatcapColor = matcapTexelToLinear( matcapColor );\n\t#else\n\t\tvec4 matcapColor = vec4( 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n}"; var meshmatcap_vert = "#define MATCAP\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#ifndef FLAT_SHADED\n\t\tvNormal = normalize( transformedNormal );\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n}"; var meshtoon_frag = "#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; var meshtoon_vert = "#define TOON\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n}"; var meshphong_frag = "#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include \n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; var meshphong_vert = "#define PHONG\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n\t#include \n}"; var meshphysical_frag = "#define STANDARD\n#ifdef PHYSICAL\n\t#define REFLECTIVITY\n\t#define CLEARCOAT\n\t#define TRANSPARENCY\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef TRANSPARENCY\n\tuniform float transparency;\n#endif\n#ifdef REFLECTIVITY\n\tuniform float reflectivity;\n#endif\n#ifdef CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheen;\n#endif\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#ifdef TRANSPARENCY\n\t\tdiffuseColor.a *= saturate( 1. - transparency + linearToRelativeLuminance( reflectedLight.directSpecular + reflectedLight.indirectSpecular ) );\n\t#endif\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; var meshphysical_vert = "#define STANDARD\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n}"; var normal_frag = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n}"; var normal_vert = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}"; var points_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n\t#include \n}"; var points_vert = "uniform float size;\nuniform float scale;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\tgl_PointSize = size;\n\t#ifdef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n}"; var shadow_frag = "uniform vec3 color;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include \n\t#include \n\t#include \n}"; var shadow_vert = "#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}"; var sprite_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include \n\t#include \n\t#include \n}"; var sprite_vert = "uniform float rotation;\nuniform vec2 center;\n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );\n\tvec2 scale;\n\tscale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) );\n\tscale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) );\n\t#ifndef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) scale *= - mvPosition.z;\n\t#endif\n\tvec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;\n\tvec2 rotatedPosition;\n\trotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n\trotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n\tmvPosition.xy += rotatedPosition;\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include \n\t#include \n\t#include \n}"; var ShaderChunk = { alphamap_fragment: alphamap_fragment, alphamap_pars_fragment: alphamap_pars_fragment, alphatest_fragment: alphatest_fragment, aomap_fragment: aomap_fragment, aomap_pars_fragment: aomap_pars_fragment, begin_vertex: begin_vertex, beginnormal_vertex: beginnormal_vertex, bsdfs: bsdfs, bumpmap_pars_fragment: bumpmap_pars_fragment, clipping_planes_fragment: clipping_planes_fragment, clipping_planes_pars_fragment: clipping_planes_pars_fragment, clipping_planes_pars_vertex: clipping_planes_pars_vertex, clipping_planes_vertex: clipping_planes_vertex, color_fragment: color_fragment, color_pars_fragment: color_pars_fragment, color_pars_vertex: color_pars_vertex, color_vertex: color_vertex, common: common, cube_uv_reflection_fragment: cube_uv_reflection_fragment, defaultnormal_vertex: defaultnormal_vertex, displacementmap_pars_vertex: displacementmap_pars_vertex, displacementmap_vertex: displacementmap_vertex, emissivemap_fragment: emissivemap_fragment, emissivemap_pars_fragment: emissivemap_pars_fragment, encodings_fragment: encodings_fragment, encodings_pars_fragment: encodings_pars_fragment, envmap_fragment: envmap_fragment, envmap_common_pars_fragment: envmap_common_pars_fragment, envmap_pars_fragment: envmap_pars_fragment, envmap_pars_vertex: envmap_pars_vertex, envmap_physical_pars_fragment: envmap_physical_pars_fragment, envmap_vertex: envmap_vertex, fog_vertex: fog_vertex, fog_pars_vertex: fog_pars_vertex, fog_fragment: fog_fragment, fog_pars_fragment: fog_pars_fragment, gradientmap_pars_fragment: gradientmap_pars_fragment, lightmap_fragment: lightmap_fragment, lightmap_pars_fragment: lightmap_pars_fragment, lights_lambert_vertex: lights_lambert_vertex, lights_pars_begin: lights_pars_begin, lights_toon_fragment: lights_toon_fragment, lights_toon_pars_fragment: lights_toon_pars_fragment, lights_phong_fragment: lights_phong_fragment, lights_phong_pars_fragment: lights_phong_pars_fragment, lights_physical_fragment: lights_physical_fragment, lights_physical_pars_fragment: lights_physical_pars_fragment, lights_fragment_begin: lights_fragment_begin, lights_fragment_maps: lights_fragment_maps, lights_fragment_end: lights_fragment_end, logdepthbuf_fragment: logdepthbuf_fragment, logdepthbuf_pars_fragment: logdepthbuf_pars_fragment, logdepthbuf_pars_vertex: logdepthbuf_pars_vertex, logdepthbuf_vertex: logdepthbuf_vertex, map_fragment: map_fragment, map_pars_fragment: map_pars_fragment, map_particle_fragment: map_particle_fragment, map_particle_pars_fragment: map_particle_pars_fragment, metalnessmap_fragment: metalnessmap_fragment, metalnessmap_pars_fragment: metalnessmap_pars_fragment, morphnormal_vertex: morphnormal_vertex, morphtarget_pars_vertex: morphtarget_pars_vertex, morphtarget_vertex: morphtarget_vertex, normal_fragment_begin: normal_fragment_begin, normal_fragment_maps: normal_fragment_maps, normalmap_pars_fragment: normalmap_pars_fragment, clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin, clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps, clearcoat_normalmap_pars_fragment: clearcoat_normalmap_pars_fragment, packing: packing, premultiplied_alpha_fragment: premultiplied_alpha_fragment, project_vertex: project_vertex, dithering_fragment: dithering_fragment, dithering_pars_fragment: dithering_pars_fragment, roughnessmap_fragment: roughnessmap_fragment, roughnessmap_pars_fragment: roughnessmap_pars_fragment, shadowmap_pars_fragment: shadowmap_pars_fragment, shadowmap_pars_vertex: shadowmap_pars_vertex, shadowmap_vertex: shadowmap_vertex, shadowmask_pars_fragment: shadowmask_pars_fragment, skinbase_vertex: skinbase_vertex, skinning_pars_vertex: skinning_pars_vertex, skinning_vertex: skinning_vertex, skinnormal_vertex: skinnormal_vertex, specularmap_fragment: specularmap_fragment, specularmap_pars_fragment: specularmap_pars_fragment, tonemapping_fragment: tonemapping_fragment, tonemapping_pars_fragment: tonemapping_pars_fragment, uv_pars_fragment: uv_pars_fragment, uv_pars_vertex: uv_pars_vertex, uv_vertex: uv_vertex, uv2_pars_fragment: uv2_pars_fragment, uv2_pars_vertex: uv2_pars_vertex, uv2_vertex: uv2_vertex, worldpos_vertex: worldpos_vertex, background_frag: background_frag, background_vert: background_vert, cube_frag: cube_frag, cube_vert: cube_vert, depth_frag: depth_frag, depth_vert: depth_vert, distanceRGBA_frag: distanceRGBA_frag, distanceRGBA_vert: distanceRGBA_vert, equirect_frag: equirect_frag, equirect_vert: equirect_vert, linedashed_frag: linedashed_frag, linedashed_vert: linedashed_vert, meshbasic_frag: meshbasic_frag, meshbasic_vert: meshbasic_vert, meshlambert_frag: meshlambert_frag, meshlambert_vert: meshlambert_vert, meshmatcap_frag: meshmatcap_frag, meshmatcap_vert: meshmatcap_vert, meshtoon_frag: meshtoon_frag, meshtoon_vert: meshtoon_vert, meshphong_frag: meshphong_frag, meshphong_vert: meshphong_vert, meshphysical_frag: meshphysical_frag, meshphysical_vert: meshphysical_vert, normal_frag: normal_frag, normal_vert: normal_vert, points_frag: points_frag, points_vert: points_vert, shadow_frag: shadow_frag, shadow_vert: shadow_vert, sprite_frag: sprite_frag, sprite_vert: sprite_vert }; /** * @author alteredq / http://alteredqualia.com/ * @author mrdoob / http://mrdoob.com/ * @author mikael emtinger / http://gomo.se/ */ var ShaderLib = { basic: { uniforms: mergeUniforms( [ UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.fog ] ), vertexShader: ShaderChunk.meshbasic_vert, fragmentShader: ShaderChunk.meshbasic_frag }, lambert: { uniforms: mergeUniforms( [ UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.fog, UniformsLib.lights, { emissive: { value: new Color( 0x000000 ) } } ] ), vertexShader: ShaderChunk.meshlambert_vert, fragmentShader: ShaderChunk.meshlambert_frag }, phong: { uniforms: mergeUniforms( [ UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, UniformsLib.lights, { emissive: { value: new Color( 0x000000 ) }, specular: { value: new Color( 0x111111 ) }, shininess: { value: 30 } } ] ), vertexShader: ShaderChunk.meshphong_vert, fragmentShader: ShaderChunk.meshphong_frag }, standard: { uniforms: mergeUniforms( [ UniformsLib.common, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.roughnessmap, UniformsLib.metalnessmap, UniformsLib.fog, UniformsLib.lights, { emissive: { value: new Color( 0x000000 ) }, roughness: { value: 0.5 }, metalness: { value: 0.5 }, envMapIntensity: { value: 1 } // temporary } ] ), vertexShader: ShaderChunk.meshphysical_vert, fragmentShader: ShaderChunk.meshphysical_frag }, toon: { uniforms: mergeUniforms( [ UniformsLib.common, UniformsLib.specularmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.gradientmap, UniformsLib.fog, UniformsLib.lights, { emissive: { value: new Color( 0x000000 ) }, specular: { value: new Color( 0x111111 ) }, shininess: { value: 30 } } ] ), vertexShader: ShaderChunk.meshtoon_vert, fragmentShader: ShaderChunk.meshtoon_frag }, matcap: { uniforms: mergeUniforms( [ UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, { matcap: { value: null } } ] ), vertexShader: ShaderChunk.meshmatcap_vert, fragmentShader: ShaderChunk.meshmatcap_frag }, points: { uniforms: mergeUniforms( [ UniformsLib.points, UniformsLib.fog ] ), vertexShader: ShaderChunk.points_vert, fragmentShader: ShaderChunk.points_frag }, dashed: { uniforms: mergeUniforms( [ UniformsLib.common, UniformsLib.fog, { scale: { value: 1 }, dashSize: { value: 1 }, totalSize: { value: 2 } } ] ), vertexShader: ShaderChunk.linedashed_vert, fragmentShader: ShaderChunk.linedashed_frag }, depth: { uniforms: mergeUniforms( [ UniformsLib.common, UniformsLib.displacementmap ] ), vertexShader: ShaderChunk.depth_vert, fragmentShader: ShaderChunk.depth_frag }, normal: { uniforms: mergeUniforms( [ UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, { opacity: { value: 1.0 } } ] ), vertexShader: ShaderChunk.normal_vert, fragmentShader: ShaderChunk.normal_frag }, sprite: { uniforms: mergeUniforms( [ UniformsLib.sprite, UniformsLib.fog ] ), vertexShader: ShaderChunk.sprite_vert, fragmentShader: ShaderChunk.sprite_frag }, background: { uniforms: { uvTransform: { value: new Matrix3() }, t2D: { value: null }, }, vertexShader: ShaderChunk.background_vert, fragmentShader: ShaderChunk.background_frag }, /* ------------------------------------------------------------------------- // Cube map shader ------------------------------------------------------------------------- */ cube: { uniforms: mergeUniforms( [ UniformsLib.envmap, { opacity: { value: 1.0 } } ] ), vertexShader: ShaderChunk.cube_vert, fragmentShader: ShaderChunk.cube_frag }, equirect: { uniforms: { tEquirect: { value: null }, }, vertexShader: ShaderChunk.equirect_vert, fragmentShader: ShaderChunk.equirect_frag }, distanceRGBA: { uniforms: mergeUniforms( [ UniformsLib.common, UniformsLib.displacementmap, { referencePosition: { value: new Vector3() }, nearDistance: { value: 1 }, farDistance: { value: 1000 } } ] ), vertexShader: ShaderChunk.distanceRGBA_vert, fragmentShader: ShaderChunk.distanceRGBA_frag }, shadow: { uniforms: mergeUniforms( [ UniformsLib.lights, UniformsLib.fog, { color: { value: new Color( 0x00000 ) }, opacity: { value: 1.0 } } ] ), vertexShader: ShaderChunk.shadow_vert, fragmentShader: ShaderChunk.shadow_frag } }; ShaderLib.physical = { uniforms: mergeUniforms( [ ShaderLib.standard.uniforms, { transparency: { value: 0 }, clearcoat: { value: 0 }, clearcoatRoughness: { value: 0 }, sheen: { value: new Color( 0x000000 ) }, clearcoatNormalScale: { value: new Vector2( 1, 1 ) }, clearcoatNormalMap: { value: null }, } ] ), vertexShader: ShaderChunk.meshphysical_vert, fragmentShader: ShaderChunk.meshphysical_frag }; /** * @author mrdoob / http://mrdoob.com/ */ function WebGLBackground( renderer, state, objects, premultipliedAlpha ) { var clearColor = new Color( 0x000000 ); var clearAlpha = 0; var planeMesh; var boxMesh; var currentBackground = null; var currentBackgroundVersion = 0; var currentTonemapping = null; function render( renderList, scene, camera, forceClear ) { var background = scene.background; // Ignore background in AR // TODO: Reconsider this. var xr = renderer.xr; var session = xr.getSession && xr.getSession(); if ( session && session.environmentBlendMode === 'additive' ) { background = null; } if ( background === null ) { setClear( clearColor, clearAlpha ); } else if ( background && background.isColor ) { setClear( background, 1 ); forceClear = true; } if ( renderer.autoClear || forceClear ) { renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil ); } if ( background && ( background.isCubeTexture || background.isWebGLCubeRenderTarget || background.mapping === CubeUVReflectionMapping ) ) { if ( boxMesh === undefined ) { boxMesh = new Mesh( new BoxBufferGeometry( 1, 1, 1 ), new ShaderMaterial( { type: 'BackgroundCubeMaterial', uniforms: cloneUniforms( ShaderLib.cube.uniforms ), vertexShader: ShaderLib.cube.vertexShader, fragmentShader: ShaderLib.cube.fragmentShader, side: BackSide, depthTest: false, depthWrite: false, fog: false } ) ); boxMesh.geometry.deleteAttribute( 'normal' ); boxMesh.geometry.deleteAttribute( 'uv' ); boxMesh.onBeforeRender = function ( renderer, scene, camera ) { this.matrixWorld.copyPosition( camera.matrixWorld ); }; // enable code injection for non-built-in material Object.defineProperty( boxMesh.material, 'envMap', { get: function () { return this.uniforms.envMap.value; } } ); objects.update( boxMesh ); } var texture = background.isWebGLCubeRenderTarget ? background.texture : background; boxMesh.material.uniforms.envMap.value = texture; boxMesh.material.uniforms.flipEnvMap.value = texture.isCubeTexture ? - 1 : 1; if ( currentBackground !== background || currentBackgroundVersion !== texture.version || currentTonemapping !== renderer.toneMapping ) { boxMesh.material.needsUpdate = true; currentBackground = background; currentBackgroundVersion = texture.version; currentTonemapping = renderer.toneMapping; } // push to the pre-sorted opaque render list renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null ); } else if ( background && background.isTexture ) { if ( planeMesh === undefined ) { planeMesh = new Mesh( new PlaneBufferGeometry( 2, 2 ), new ShaderMaterial( { type: 'BackgroundMaterial', uniforms: cloneUniforms( ShaderLib.background.uniforms ), vertexShader: ShaderLib.background.vertexShader, fragmentShader: ShaderLib.background.fragmentShader, side: FrontSide, depthTest: false, depthWrite: false, fog: false } ) ); planeMesh.geometry.deleteAttribute( 'normal' ); // enable code injection for non-built-in material Object.defineProperty( planeMesh.material, 'map', { get: function () { return this.uniforms.t2D.value; } } ); objects.update( planeMesh ); } planeMesh.material.uniforms.t2D.value = background; if ( background.matrixAutoUpdate === true ) { background.updateMatrix(); } planeMesh.material.uniforms.uvTransform.value.copy( background.matrix ); if ( currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping ) { planeMesh.material.needsUpdate = true; currentBackground = background; currentBackgroundVersion = background.version; currentTonemapping = renderer.toneMapping; } // push to the pre-sorted opaque render list renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null ); } } function setClear( color, alpha ) { state.buffers.color.setClear( color.r, color.g, color.b, alpha, premultipliedAlpha ); } return { getClearColor: function () { return clearColor; }, setClearColor: function ( color, alpha ) { clearColor.set( color ); clearAlpha = alpha !== undefined ? alpha : 1; setClear( clearColor, clearAlpha ); }, getClearAlpha: function () { return clearAlpha; }, setClearAlpha: function ( alpha ) { clearAlpha = alpha; setClear( clearColor, clearAlpha ); }, render: render }; } /** * @author mrdoob / http://mrdoob.com/ */ function WebGLBufferRenderer( gl, extensions, info, capabilities ) { var isWebGL2 = capabilities.isWebGL2; var mode; function setMode( value ) { mode = value; } function render( start, count ) { gl.drawArrays( mode, start, count ); info.update( count, mode ); } function renderInstances( geometry, start, count, primcount ) { if ( primcount === 0 ) { return; } var extension, methodName; if ( isWebGL2 ) { extension = gl; methodName = 'drawArraysInstanced'; } else { extension = extensions.get( 'ANGLE_instanced_arrays' ); methodName = 'drawArraysInstancedANGLE'; if ( extension === null ) { console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' ); return; } } extension[ methodName ]( mode, start, count, primcount ); info.update( count, mode, primcount ); } // this.setMode = setMode; this.render = render; this.renderInstances = renderInstances; } /** * @author mrdoob / http://mrdoob.com/ */ function WebGLCapabilities( gl, extensions, parameters ) { var maxAnisotropy; function getMaxAnisotropy() { if ( maxAnisotropy !== undefined ) { return maxAnisotropy; } var extension = extensions.get( 'EXT_texture_filter_anisotropic' ); if ( extension !== null ) { maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT ); } else { maxAnisotropy = 0; } return maxAnisotropy; } function getMaxPrecision( precision ) { if ( precision === 'highp' ) { if ( gl.getShaderPrecisionFormat( 35633, 36338 ).precision > 0 && gl.getShaderPrecisionFormat( 35632, 36338 ).precision > 0 ) { return 'highp'; } precision = 'mediump'; } if ( precision === 'mediump' ) { if ( gl.getShaderPrecisionFormat( 35633, 36337 ).precision > 0 && gl.getShaderPrecisionFormat( 35632, 36337 ).precision > 0 ) { return 'mediump'; } } return 'lowp'; } /* eslint-disable no-undef */ var isWebGL2 = ( typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext ) || ( typeof WebGL2ComputeRenderingContext !== 'undefined' && gl instanceof WebGL2ComputeRenderingContext ); /* eslint-enable no-undef */ var precision = parameters.precision !== undefined ? parameters.precision : 'highp'; var maxPrecision = getMaxPrecision( precision ); if ( maxPrecision !== precision ) { console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' ); precision = maxPrecision; } var logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true; var maxTextures = gl.getParameter( 34930 ); var maxVertexTextures = gl.getParameter( 35660 ); var maxTextureSize = gl.getParameter( 3379 ); var maxCubemapSize = gl.getParameter( 34076 ); var maxAttributes = gl.getParameter( 34921 ); var maxVertexUniforms = gl.getParameter( 36347 ); var maxVaryings = gl.getParameter( 36348 ); var maxFragmentUniforms = gl.getParameter( 36349 ); var vertexTextures = maxVertexTextures > 0; var floatFragmentTextures = isWebGL2 || !! extensions.get( 'OES_texture_float' ); var floatVertexTextures = vertexTextures && floatFragmentTextures; var maxSamples = isWebGL2 ? gl.getParameter( 36183 ) : 0; return { isWebGL2: isWebGL2, getMaxAnisotropy: getMaxAnisotropy, getMaxPrecision: getMaxPrecision, precision: precision, logarithmicDepthBuffer: logarithmicDepthBuffer, maxTextures: maxTextures, maxVertexTextures: maxVertexTextures, maxTextureSize: maxTextureSize, maxCubemapSize: maxCubemapSize, maxAttributes: maxAttributes, maxVertexUniforms: maxVertexUniforms, maxVaryings: maxVaryings, maxFragmentUniforms: maxFragmentUniforms, vertexTextures: vertexTextures, floatFragmentTextures: floatFragmentTextures, floatVertexTextures: floatVertexTextures, maxSamples: maxSamples }; } /** * @author tschw */ function WebGLClipping() { var scope = this, globalState = null, numGlobalPlanes = 0, localClippingEnabled = false, renderingShadows = false, plane = new Plane(), viewNormalMatrix = new Matrix3(), uniform = { value: null, needsUpdate: false }; this.uniform = uniform; this.numPlanes = 0; this.numIntersection = 0; this.init = function ( planes, enableLocalClipping, camera ) { var enabled = planes.length !== 0 || enableLocalClipping || // enable state of previous frame - the clipping code has to // run another frame in order to reset the state: numGlobalPlanes !== 0 || localClippingEnabled; localClippingEnabled = enableLocalClipping; globalState = projectPlanes( planes, camera, 0 ); numGlobalPlanes = planes.length; return enabled; }; this.beginShadows = function () { renderingShadows = true; projectPlanes( null ); }; this.endShadows = function () { renderingShadows = false; resetGlobalState(); }; this.setState = function ( planes, clipIntersection, clipShadows, camera, cache, fromCache ) { if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) { // there's no local clipping if ( renderingShadows ) { // there's no global clipping projectPlanes( null ); } else { resetGlobalState(); } } else { var nGlobal = renderingShadows ? 0 : numGlobalPlanes, lGlobal = nGlobal * 4, dstArray = cache.clippingState || null; uniform.value = dstArray; // ensure unique state dstArray = projectPlanes( planes, camera, lGlobal, fromCache ); for ( var i = 0; i !== lGlobal; ++ i ) { dstArray[ i ] = globalState[ i ]; } cache.clippingState = dstArray; this.numIntersection = clipIntersection ? this.numPlanes : 0; this.numPlanes += nGlobal; } }; function resetGlobalState() { if ( uniform.value !== globalState ) { uniform.value = globalState; uniform.needsUpdate = numGlobalPlanes > 0; } scope.numPlanes = numGlobalPlanes; scope.numIntersection = 0; } function projectPlanes( planes, camera, dstOffset, skipTransform ) { var nPlanes = planes !== null ? planes.length : 0, dstArray = null; if ( nPlanes !== 0 ) { dstArray = uniform.value; if ( skipTransform !== true || dstArray === null ) { var flatSize = dstOffset + nPlanes * 4, viewMatrix = camera.matrixWorldInverse; viewNormalMatrix.getNormalMatrix( viewMatrix ); if ( dstArray === null || dstArray.length < flatSize ) { dstArray = new Float32Array( flatSize ); } for ( var i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) { plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix ); plane.normal.toArray( dstArray, i4 ); dstArray[ i4 + 3 ] = plane.constant; } } uniform.value = dstArray; uniform.needsUpdate = true; } scope.numPlanes = nPlanes; return dstArray; } } /** * @author mrdoob / http://mrdoob.com/ */ function WebGLExtensions( gl ) { var extensions = {}; return { get: function ( name ) { if ( extensions[ name ] !== undefined ) { return extensions[ name ]; } var extension; switch ( name ) { case 'WEBGL_depth_texture': extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' ); break; case 'EXT_texture_filter_anisotropic': extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' ); break; case 'WEBGL_compressed_texture_s3tc': extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' ); break; case 'WEBGL_compressed_texture_pvrtc': extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' ); break; default: extension = gl.getExtension( name ); } if ( extension === null ) { console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' ); } extensions[ name ] = extension; return extension; } }; } /** * @author mrdoob / http://mrdoob.com/ */ function WebGLGeometries( gl, attributes, info ) { var geometries = new WeakMap(); var wireframeAttributes = new WeakMap(); function onGeometryDispose( event ) { var geometry = event.target; var buffergeometry = geometries.get( geometry ); if ( buffergeometry.index !== null ) { attributes.remove( buffergeometry.index ); } for ( var name in buffergeometry.attributes ) { attributes.remove( buffergeometry.attributes[ name ] ); } geometry.removeEventListener( 'dispose', onGeometryDispose ); geometries.delete( geometry ); var attribute = wireframeAttributes.get( buffergeometry ); if ( attribute ) { attributes.remove( attribute ); wireframeAttributes.delete( buffergeometry ); } // info.memory.geometries --; } function get( object, geometry ) { var buffergeometry = geometries.get( geometry ); if ( buffergeometry ) { return buffergeometry; } geometry.addEventListener( 'dispose', onGeometryDispose ); if ( geometry.isBufferGeometry ) { buffergeometry = geometry; } else if ( geometry.isGeometry ) { if ( geometry._bufferGeometry === undefined ) { geometry._bufferGeometry = new BufferGeometry().setFromObject( object ); } buffergeometry = geometry._bufferGeometry; } geometries.set( geometry, buffergeometry ); info.memory.geometries ++; return buffergeometry; } function update( geometry ) { var index = geometry.index; var geometryAttributes = geometry.attributes; if ( index !== null ) { attributes.update( index, 34963 ); } for ( var name in geometryAttributes ) { attributes.update( geometryAttributes[ name ], 34962 ); } // morph targets var morphAttributes = geometry.morphAttributes; for ( var name in morphAttributes ) { var array = morphAttributes[ name ]; for ( var i = 0, l = array.length; i < l; i ++ ) { attributes.update( array[ i ], 34962 ); } } } function updateWireframeAttribute( geometry ) { var indices = []; var geometryIndex = geometry.index; var geometryPosition = geometry.attributes.position; var version = 0; if ( geometryIndex !== null ) { var array = geometryIndex.array; version = geometryIndex.version; for ( var i = 0, l = array.length; i < l; i += 3 ) { var a = array[ i + 0 ]; var b = array[ i + 1 ]; var c = array[ i + 2 ]; indices.push( a, b, b, c, c, a ); } } else { var array = geometryPosition.array; version = geometryPosition.version; for ( var i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) { var a = i + 0; var b = i + 1; var c = i + 2; indices.push( a, b, b, c, c, a ); } } var attribute = new ( arrayMax( indices ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 ); attribute.version = version; attributes.update( attribute, 34963 ); // var previousAttribute = wireframeAttributes.get( geometry ); if ( previousAttribute ) { attributes.remove( previousAttribute ); } // wireframeAttributes.set( geometry, attribute ); } function getWireframeAttribute( geometry ) { var currentAttribute = wireframeAttributes.get( geometry ); if ( currentAttribute ) { var geometryIndex = geometry.index; if ( geometryIndex !== null ) { // if the attribute is obsolete, create a new one if ( currentAttribute.version < geometryIndex.version ) { updateWireframeAttribute( geometry ); } } } else { updateWireframeAttribute( geometry ); } return wireframeAttributes.get( geometry ); } return { get: get, update: update, getWireframeAttribute: getWireframeAttribute }; } /** * @author mrdoob / http://mrdoob.com/ */ function WebGLIndexedBufferRenderer( gl, extensions, info, capabilities ) { var isWebGL2 = capabilities.isWebGL2; var mode; function setMode( value ) { mode = value; } var type, bytesPerElement; function setIndex( value ) { type = value.type; bytesPerElement = value.bytesPerElement; } function render( start, count ) { gl.drawElements( mode, count, type, start * bytesPerElement ); info.update( count, mode ); } function renderInstances( geometry, start, count, primcount ) { if ( primcount === 0 ) { return; } var extension, methodName; if ( isWebGL2 ) { extension = gl; methodName = 'drawElementsInstanced'; } else { extension = extensions.get( 'ANGLE_instanced_arrays' ); methodName = 'drawElementsInstancedANGLE'; if ( extension === null ) { console.error( 'THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' ); return; } } extension[ methodName ]( mode, count, type, start * bytesPerElement, primcount ); info.update( count, mode, primcount ); } // this.setMode = setMode; this.setIndex = setIndex; this.render = render; this.renderInstances = renderInstances; } /** * @author Mugen87 / https://github.com/Mugen87 */ function WebGLInfo( gl ) { var memory = { geometries: 0, textures: 0 }; var render = { frame: 0, calls: 0, triangles: 0, points: 0, lines: 0 }; function update( count, mode, instanceCount ) { instanceCount = instanceCount || 1; render.calls ++; switch ( mode ) { case 4: render.triangles += instanceCount * ( count / 3 ); break; case 1: render.lines += instanceCount * ( count / 2 ); break; case 3: render.lines += instanceCount * ( count - 1 ); break; case 2: render.lines += instanceCount * count; break; case 0: render.points += instanceCount * count; break; default: console.error( 'THREE.WebGLInfo: Unknown draw mode:', mode ); break; } } function reset() { render.frame ++; render.calls = 0; render.triangles = 0; render.points = 0; render.lines = 0; } return { memory: memory, render: render, programs: null, autoReset: true, reset: reset, update: update }; } /** * @author mrdoob / http://mrdoob.com/ */ function absNumericalSort( a, b ) { return Math.abs( b[ 1 ] ) - Math.abs( a[ 1 ] ); } function WebGLMorphtargets( gl ) { var influencesList = {}; var morphInfluences = new Float32Array( 8 ); function update( object, geometry, material, program ) { var objectInfluences = object.morphTargetInfluences; // When object doesn't have morph target influences defined, we treat it as a 0-length array // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences var length = objectInfluences === undefined ? 0 : objectInfluences.length; var influences = influencesList[ geometry.id ]; if ( influences === undefined ) { // initialise list influences = []; for ( var i = 0; i < length; i ++ ) { influences[ i ] = [ i, 0 ]; } influencesList[ geometry.id ] = influences; } var morphTargets = material.morphTargets && geometry.morphAttributes.position; var morphNormals = material.morphNormals && geometry.morphAttributes.normal; // Remove current morphAttributes for ( var i = 0; i < length; i ++ ) { var influence = influences[ i ]; if ( influence[ 1 ] !== 0 ) { if ( morphTargets ) { geometry.deleteAttribute( 'morphTarget' + i ); } if ( morphNormals ) { geometry.deleteAttribute( 'morphNormal' + i ); } } } // Collect influences for ( var i = 0; i < length; i ++ ) { var influence = influences[ i ]; influence[ 0 ] = i; influence[ 1 ] = objectInfluences[ i ]; } influences.sort( absNumericalSort ); // Add morphAttributes var morphInfluencesSum = 0; for ( var i = 0; i < 8; i ++ ) { var influence = influences[ i ]; if ( influence ) { var index = influence[ 0 ]; var value = influence[ 1 ]; if ( value ) { if ( morphTargets ) { geometry.setAttribute( 'morphTarget' + i, morphTargets[ index ] ); } if ( morphNormals ) { geometry.setAttribute( 'morphNormal' + i, morphNormals[ index ] ); } morphInfluences[ i ] = value; morphInfluencesSum += value; continue; } } morphInfluences[ i ] = 0; } // GLSL shader uses formula baseinfluence * base + sum(target * influence) // This allows us to switch between absolute morphs and relative morphs without changing shader code // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence) var morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum; program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence ); program.getUniforms().setValue( gl, 'morphTargetInfluences', morphInfluences ); } return { update: update }; } /** * @author mrdoob / http://mrdoob.com/ */ function WebGLObjects( gl, geometries, attributes, info ) { var updateList = {}; function update( object ) { var frame = info.render.frame; var geometry = object.geometry; var buffergeometry = geometries.get( object, geometry ); // Update once per frame if ( updateList[ buffergeometry.id ] !== frame ) { if ( geometry.isGeometry ) { buffergeometry.updateFromObject( object ); } geometries.update( buffergeometry ); updateList[ buffergeometry.id ] = frame; } if ( object.isInstancedMesh ) { attributes.update( object.instanceMatrix, 34962 ); } return buffergeometry; } function dispose() { updateList = {}; } return { update: update, dispose: dispose }; } /** * @author mrdoob / http://mrdoob.com/ */ function CubeTexture( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) { images = images !== undefined ? images : []; mapping = mapping !== undefined ? mapping : CubeReflectionMapping; format = format !== undefined ? format : RGBFormat; Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); this.flipY = false; } CubeTexture.prototype = Object.create( Texture.prototype ); CubeTexture.prototype.constructor = CubeTexture; CubeTexture.prototype.isCubeTexture = true; Object.defineProperty( CubeTexture.prototype, 'images', { get: function () { return this.image; }, set: function ( value ) { this.image = value; } } ); /** * @author Takahiro https://github.com/takahirox */ function DataTexture2DArray( data, width, height, depth ) { Texture.call( this, null ); this.image = { data: data || null, width: width || 1, height: height || 1, depth: depth || 1 }; this.magFilter = NearestFilter; this.minFilter = NearestFilter; this.wrapR = ClampToEdgeWrapping; this.generateMipmaps = false; this.flipY = false; this.needsUpdate = true; } DataTexture2DArray.prototype = Object.create( Texture.prototype ); DataTexture2DArray.prototype.constructor = DataTexture2DArray; DataTexture2DArray.prototype.isDataTexture2DArray = true; /** * @author Artur Trzesiok */ function DataTexture3D( data, width, height, depth ) { // We're going to add .setXXX() methods for setting properties later. // Users can still set in DataTexture3D directly. // // var texture = new THREE.DataTexture3D( data, width, height, depth ); // texture.anisotropy = 16; // // See #14839 Texture.call( this, null ); this.image = { data: data || null, width: width || 1, height: height || 1, depth: depth || 1 }; this.magFilter = NearestFilter; this.minFilter = NearestFilter; this.wrapR = ClampToEdgeWrapping; this.generateMipmaps = false; this.flipY = false; this.needsUpdate = true; } DataTexture3D.prototype = Object.create( Texture.prototype ); DataTexture3D.prototype.constructor = DataTexture3D; DataTexture3D.prototype.isDataTexture3D = true; /** * @author tschw * @author Mugen87 / https://github.com/Mugen87 * @author mrdoob / http://mrdoob.com/ * * Uniforms of a program. * Those form a tree structure with a special top-level container for the root, * which you get by calling 'new WebGLUniforms( gl, program )'. * * * Properties of inner nodes including the top-level container: * * .seq - array of nested uniforms * .map - nested uniforms by name * * * Methods of all nodes except the top-level container: * * .setValue( gl, value, [textures] ) * * uploads a uniform value(s) * the 'textures' parameter is needed for sampler uniforms * * * Static methods of the top-level container (textures factorizations): * * .upload( gl, seq, values, textures ) * * sets uniforms in 'seq' to 'values[id].value' * * .seqWithValue( seq, values ) : filteredSeq * * filters 'seq' entries with corresponding entry in values * * * Methods of the top-level container (textures factorizations): * * .setValue( gl, name, value, textures ) * * sets uniform with name 'name' to 'value' * * .setOptional( gl, obj, prop ) * * like .set for an optional property of the object * */ var emptyTexture = new Texture(); var emptyTexture2dArray = new DataTexture2DArray(); var emptyTexture3d = new DataTexture3D(); var emptyCubeTexture = new CubeTexture(); // --- Utilities --- // Array Caches (provide typed arrays for temporary by size) var arrayCacheF32 = []; var arrayCacheI32 = []; // Float32Array caches used for uploading Matrix uniforms var mat4array = new Float32Array( 16 ); var mat3array = new Float32Array( 9 ); var mat2array = new Float32Array( 4 ); // Flattening for arrays of vectors and matrices function flatten( array, nBlocks, blockSize ) { var firstElem = array[ 0 ]; if ( firstElem <= 0 || firstElem > 0 ) { return array; } // unoptimized: ! isNaN( firstElem ) // see http://jacksondunstan.com/articles/983 var n = nBlocks * blockSize, r = arrayCacheF32[ n ]; if ( r === undefined ) { r = new Float32Array( n ); arrayCacheF32[ n ] = r; } if ( nBlocks !== 0 ) { firstElem.toArray( r, 0 ); for ( var i = 1, offset = 0; i !== nBlocks; ++ i ) { offset += blockSize; array[ i ].toArray( r, offset ); } } return r; } function arraysEqual( a, b ) { if ( a.length !== b.length ) { return false; } for ( var i = 0, l = a.length; i < l; i ++ ) { if ( a[ i ] !== b[ i ] ) { return false; } } return true; } function copyArray( a, b ) { for ( var i = 0, l = b.length; i < l; i ++ ) { a[ i ] = b[ i ]; } } // Texture unit allocation function allocTexUnits( textures, n ) { var r = arrayCacheI32[ n ]; if ( r === undefined ) { r = new Int32Array( n ); arrayCacheI32[ n ] = r; } for ( var i = 0; i !== n; ++ i ) { r[ i ] = textures.allocateTextureUnit(); } return r; } // --- Setters --- // Note: Defining these methods externally, because they come in a bunch // and this way their names minify. // Single scalar function setValueV1f( gl, v ) { var cache = this.cache; if ( cache[ 0 ] === v ) { return; } gl.uniform1f( this.addr, v ); cache[ 0 ] = v; } // Single float vector (from flat array or THREE.VectorN) function setValueV2f( gl, v ) { var cache = this.cache; if ( v.x !== undefined ) { if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) { gl.uniform2f( this.addr, v.x, v.y ); cache[ 0 ] = v.x; cache[ 1 ] = v.y; } } else { if ( arraysEqual( cache, v ) ) { return; } gl.uniform2fv( this.addr, v ); copyArray( cache, v ); } } function setValueV3f( gl, v ) { var cache = this.cache; if ( v.x !== undefined ) { if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) { gl.uniform3f( this.addr, v.x, v.y, v.z ); cache[ 0 ] = v.x; cache[ 1 ] = v.y; cache[ 2 ] = v.z; } } else if ( v.r !== undefined ) { if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) { gl.uniform3f( this.addr, v.r, v.g, v.b ); cache[ 0 ] = v.r; cache[ 1 ] = v.g; cache[ 2 ] = v.b; } } else { if ( arraysEqual( cache, v ) ) { return; } gl.uniform3fv( this.addr, v ); copyArray( cache, v ); } } function setValueV4f( gl, v ) { var cache = this.cache; if ( v.x !== undefined ) { if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) { gl.uniform4f( this.addr, v.x, v.y, v.z, v.w ); cache[ 0 ] = v.x; cache[ 1 ] = v.y; cache[ 2 ] = v.z; cache[ 3 ] = v.w; } } else { if ( arraysEqual( cache, v ) ) { return; } gl.uniform4fv( this.addr, v ); copyArray( cache, v ); } } // Single matrix (from flat array or MatrixN) function setValueM2( gl, v ) { var cache = this.cache; var elements = v.elements; if ( elements === undefined ) { if ( arraysEqual( cache, v ) ) { return; } gl.uniformMatrix2fv( this.addr, false, v ); copyArray( cache, v ); } else { if ( arraysEqual( cache, elements ) ) { return; } mat2array.set( elements ); gl.uniformMatrix2fv( this.addr, false, mat2array ); copyArray( cache, elements ); } } function setValueM3( gl, v ) { var cache = this.cache; var elements = v.elements; if ( elements === undefined ) { if ( arraysEqual( cache, v ) ) { return; } gl.uniformMatrix3fv( this.addr, false, v ); copyArray( cache, v ); } else { if ( arraysEqual( cache, elements ) ) { return; } mat3array.set( elements ); gl.uniformMatrix3fv( this.addr, false, mat3array ); copyArray( cache, elements ); } } function setValueM4( gl, v ) { var cache = this.cache; var elements = v.elements; if ( elements === undefined ) { if ( arraysEqual( cache, v ) ) { return; } gl.uniformMatrix4fv( this.addr, false, v ); copyArray( cache, v ); } else { if ( arraysEqual( cache, elements ) ) { return; } mat4array.set( elements ); gl.uniformMatrix4fv( this.addr, false, mat4array ); copyArray( cache, elements ); } } // Single texture (2D / Cube) function setValueT1( gl, v, textures ) { var cache = this.cache; var unit = textures.allocateTextureUnit(); if ( cache[ 0 ] !== unit ) { gl.uniform1i( this.addr, unit ); cache[ 0 ] = unit; } textures.safeSetTexture2D( v || emptyTexture, unit ); } function setValueT2DArray1( gl, v, textures ) { var cache = this.cache; var unit = textures.allocateTextureUnit(); if ( cache[ 0 ] !== unit ) { gl.uniform1i( this.addr, unit ); cache[ 0 ] = unit; } textures.setTexture2DArray( v || emptyTexture2dArray, unit ); } function setValueT3D1( gl, v, textures ) { var cache = this.cache; var unit = textures.allocateTextureUnit(); if ( cache[ 0 ] !== unit ) { gl.uniform1i( this.addr, unit ); cache[ 0 ] = unit; } textures.setTexture3D( v || emptyTexture3d, unit ); } function setValueT6( gl, v, textures ) { var cache = this.cache; var unit = textures.allocateTextureUnit(); if ( cache[ 0 ] !== unit ) { gl.uniform1i( this.addr, unit ); cache[ 0 ] = unit; } textures.safeSetTextureCube( v || emptyCubeTexture, unit ); } // Integer / Boolean vectors or arrays thereof (always flat arrays) function setValueV1i( gl, v ) { var cache = this.cache; if ( cache[ 0 ] === v ) { return; } gl.uniform1i( this.addr, v ); cache[ 0 ] = v; } function setValueV2i( gl, v ) { var cache = this.cache; if ( arraysEqual( cache, v ) ) { return; } gl.uniform2iv( this.addr, v ); copyArray( cache, v ); } function setValueV3i( gl, v ) { var cache = this.cache; if ( arraysEqual( cache, v ) ) { return; } gl.uniform3iv( this.addr, v ); copyArray( cache, v ); } function setValueV4i( gl, v ) { var cache = this.cache; if ( arraysEqual( cache, v ) ) { return; } gl.uniform4iv( this.addr, v ); copyArray( cache, v ); } // uint function setValueV1ui( gl, v ) { var cache = this.cache; if ( cache[ 0 ] === v ) { return; } gl.uniform1ui( this.addr, v ); cache[ 0 ] = v; } // Helper to pick the right setter for the singular case function getSingularSetter( type ) { switch ( type ) { case 0x1406: return setValueV1f; // FLOAT case 0x8b50: return setValueV2f; // _VEC2 case 0x8b51: return setValueV3f; // _VEC3 case 0x8b52: return setValueV4f; // _VEC4 case 0x8b5a: return setValueM2; // _MAT2 case 0x8b5b: return setValueM3; // _MAT3 case 0x8b5c: return setValueM4; // _MAT4 case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2 case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3 case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4 case 0x1405: return setValueV1ui; // UINT case 0x8b5e: // SAMPLER_2D case 0x8d66: // SAMPLER_EXTERNAL_OES case 0x8dca: // INT_SAMPLER_2D case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D case 0x8b62: // SAMPLER_2D_SHADOW return setValueT1; case 0x8b5f: // SAMPLER_3D case 0x8dcb: // INT_SAMPLER_3D case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D return setValueT3D1; case 0x8b60: // SAMPLER_CUBE case 0x8dcc: // INT_SAMPLER_CUBE case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE case 0x8dc5: // SAMPLER_CUBE_SHADOW return setValueT6; case 0x8dc1: // SAMPLER_2D_ARRAY case 0x8dcf: // INT_SAMPLER_2D_ARRAY case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW return setValueT2DArray1; } } // Array of scalars function setValueV1fArray( gl, v ) { gl.uniform1fv( this.addr, v ); } // Integer / Boolean vectors or arrays thereof (always flat arrays) function setValueV1iArray( gl, v ) { gl.uniform1iv( this.addr, v ); } function setValueV2iArray( gl, v ) { gl.uniform2iv( this.addr, v ); } function setValueV3iArray( gl, v ) { gl.uniform3iv( this.addr, v ); } function setValueV4iArray( gl, v ) { gl.uniform4iv( this.addr, v ); } // Array of vectors (flat or from THREE classes) function setValueV2fArray( gl, v ) { var data = flatten( v, this.size, 2 ); gl.uniform2fv( this.addr, data ); } function setValueV3fArray( gl, v ) { var data = flatten( v, this.size, 3 ); gl.uniform3fv( this.addr, data ); } function setValueV4fArray( gl, v ) { var data = flatten( v, this.size, 4 ); gl.uniform4fv( this.addr, data ); } // Array of matrices (flat or from THREE clases) function setValueM2Array( gl, v ) { var data = flatten( v, this.size, 4 ); gl.uniformMatrix2fv( this.addr, false, data ); } function setValueM3Array( gl, v ) { var data = flatten( v, this.size, 9 ); gl.uniformMatrix3fv( this.addr, false, data ); } function setValueM4Array( gl, v ) { var data = flatten( v, this.size, 16 ); gl.uniformMatrix4fv( this.addr, false, data ); } // Array of textures (2D / Cube) function setValueT1Array( gl, v, textures ) { var n = v.length; var units = allocTexUnits( textures, n ); gl.uniform1iv( this.addr, units ); for ( var i = 0; i !== n; ++ i ) { textures.safeSetTexture2D( v[ i ] || emptyTexture, units[ i ] ); } } function setValueT6Array( gl, v, textures ) { var n = v.length; var units = allocTexUnits( textures, n ); gl.uniform1iv( this.addr, units ); for ( var i = 0; i !== n; ++ i ) { textures.safeSetTextureCube( v[ i ] || emptyCubeTexture, units[ i ] ); } } // Helper to pick the right setter for a pure (bottom-level) array function getPureArraySetter( type ) { switch ( type ) { case 0x1406: return setValueV1fArray; // FLOAT case 0x8b50: return setValueV2fArray; // _VEC2 case 0x8b51: return setValueV3fArray; // _VEC3 case 0x8b52: return setValueV4fArray; // _VEC4 case 0x8b5a: return setValueM2Array; // _MAT2 case 0x8b5b: return setValueM3Array; // _MAT3 case 0x8b5c: return setValueM4Array; // _MAT4 case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2 case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3 case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4 case 0x8b5e: // SAMPLER_2D case 0x8d66: // SAMPLER_EXTERNAL_OES case 0x8dca: // INT_SAMPLER_2D case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D case 0x8b62: // SAMPLER_2D_SHADOW return setValueT1Array; case 0x8b60: // SAMPLER_CUBE case 0x8dcc: // INT_SAMPLER_CUBE case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE case 0x8dc5: // SAMPLER_CUBE_SHADOW return setValueT6Array; } } // --- Uniform Classes --- function SingleUniform( id, activeInfo, addr ) { this.id = id; this.addr = addr; this.cache = []; this.setValue = getSingularSetter( activeInfo.type ); // this.path = activeInfo.name; // DEBUG } function PureArrayUniform( id, activeInfo, addr ) { this.id = id; this.addr = addr; this.cache = []; this.size = activeInfo.size; this.setValue = getPureArraySetter( activeInfo.type ); // this.path = activeInfo.name; // DEBUG } PureArrayUniform.prototype.updateCache = function ( data ) { var cache = this.cache; if ( data instanceof Float32Array && cache.length !== data.length ) { this.cache = new Float32Array( data.length ); } copyArray( cache, data ); }; function StructuredUniform( id ) { this.id = id; this.seq = []; this.map = {}; } StructuredUniform.prototype.setValue = function ( gl, value, textures ) { var seq = this.seq; for ( var i = 0, n = seq.length; i !== n; ++ i ) { var u = seq[ i ]; u.setValue( gl, value[ u.id ], textures ); } }; // --- Top-level --- // Parser - builds up the property tree from the path strings var RePathPart = /([\w\d_]+)(\])?(\[|\.)?/g; // extracts // - the identifier (member name or array index) // - followed by an optional right bracket (found when array index) // - followed by an optional left bracket or dot (type of subscript) // // Note: These portions can be read in a non-overlapping fashion and // allow straightforward parsing of the hierarchy that WebGL encodes // in the uniform names. function addUniform( container, uniformObject ) { container.seq.push( uniformObject ); container.map[ uniformObject.id ] = uniformObject; } function parseUniform( activeInfo, addr, container ) { var path = activeInfo.name, pathLength = path.length; // reset RegExp object, because of the early exit of a previous run RePathPart.lastIndex = 0; while ( true ) { var match = RePathPart.exec( path ), matchEnd = RePathPart.lastIndex, id = match[ 1 ], idIsIndex = match[ 2 ] === ']', subscript = match[ 3 ]; if ( idIsIndex ) { id = id | 0; } // convert to integer if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) { // bare name or "pure" bottom-level array "[0]" suffix addUniform( container, subscript === undefined ? new SingleUniform( id, activeInfo, addr ) : new PureArrayUniform( id, activeInfo, addr ) ); break; } else { // step into inner node / create it in case it doesn't exist var map = container.map, next = map[ id ]; if ( next === undefined ) { next = new StructuredUniform( id ); addUniform( container, next ); } container = next; } } } // Root Container function WebGLUniforms( gl, program ) { this.seq = []; this.map = {}; var n = gl.getProgramParameter( program, 35718 ); for ( var i = 0; i < n; ++ i ) { var info = gl.getActiveUniform( program, i ), addr = gl.getUniformLocation( program, info.name ); parseUniform( info, addr, this ); } } WebGLUniforms.prototype.setValue = function ( gl, name, value, textures ) { var u = this.map[ name ]; if ( u !== undefined ) { u.setValue( gl, value, textures ); } }; WebGLUniforms.prototype.setOptional = function ( gl, object, name ) { var v = object[ name ]; if ( v !== undefined ) { this.setValue( gl, name, v ); } }; // Static interface WebGLUniforms.upload = function ( gl, seq, values, textures ) { for ( var i = 0, n = seq.length; i !== n; ++ i ) { var u = seq[ i ], v = values[ u.id ]; if ( v.needsUpdate !== false ) { // note: always updating when .needsUpdate is undefined u.setValue( gl, v.value, textures ); } } }; WebGLUniforms.seqWithValue = function ( seq, values ) { var r = []; for ( var i = 0, n = seq.length; i !== n; ++ i ) { var u = seq[ i ]; if ( u.id in values ) { r.push( u ); } } return r; }; /** * @author mrdoob / http://mrdoob.com/ */ function WebGLShader( gl, type, string ) { var shader = gl.createShader( type ); gl.shaderSource( shader, string ); gl.compileShader( shader ); return shader; } /** * @author mrdoob / http://mrdoob.com/ */ var programIdCount = 0; function addLineNumbers( string ) { var lines = string.split( '\n' ); for ( var i = 0; i < lines.length; i ++ ) { lines[ i ] = ( i + 1 ) + ': ' + lines[ i ]; } return lines.join( '\n' ); } function getEncodingComponents( encoding ) { switch ( encoding ) { case LinearEncoding: return [ 'Linear', '( value )' ]; case sRGBEncoding: return [ 'sRGB', '( value )' ]; case RGBEEncoding: return [ 'RGBE', '( value )' ]; case RGBM7Encoding: return [ 'RGBM', '( value, 7.0 )' ]; case RGBM16Encoding: return [ 'RGBM', '( value, 16.0 )' ]; case RGBDEncoding: return [ 'RGBD', '( value, 256.0 )' ]; case GammaEncoding: return [ 'Gamma', '( value, float( GAMMA_FACTOR ) )' ]; case LogLuvEncoding: return [ 'LogLuv', '( value )' ]; default: throw new Error( 'unsupported encoding: ' + encoding ); } } function getShaderErrors( gl, shader, type ) { var status = gl.getShaderParameter( shader, 35713 ); var log = gl.getShaderInfoLog( shader ).trim(); if ( status && log === '' ) { return ''; } // --enable-privileged-webgl-extension // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) ); var source = gl.getShaderSource( shader ); return 'THREE.WebGLShader: gl.getShaderInfoLog() ' + type + '\n' + log + addLineNumbers( source ); } function getTexelDecodingFunction( functionName, encoding ) { var components = getEncodingComponents( encoding ); return 'vec4 ' + functionName + '( vec4 value ) { return ' + components[ 0 ] + 'ToLinear' + components[ 1 ] + '; }'; } function getTexelEncodingFunction( functionName, encoding ) { var components = getEncodingComponents( encoding ); return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[ 0 ] + components[ 1 ] + '; }'; } function getToneMappingFunction( functionName, toneMapping ) { var toneMappingName; switch ( toneMapping ) { case LinearToneMapping: toneMappingName = 'Linear'; break; case ReinhardToneMapping: toneMappingName = 'Reinhard'; break; case Uncharted2ToneMapping: toneMappingName = 'Uncharted2'; break; case CineonToneMapping: toneMappingName = 'OptimizedCineon'; break; case ACESFilmicToneMapping: toneMappingName = 'ACESFilmic'; break; default: throw new Error( 'unsupported toneMapping: ' + toneMapping ); } return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }'; } function generateExtensions( parameters ) { var chunks = [ ( parameters.extensionDerivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.tangentSpaceNormalMap || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === 'physical' ) ? '#extension GL_OES_standard_derivatives : enable' : '', ( parameters.extensionFragDepth || parameters.logarithmicDepthBuffer ) && parameters.rendererExtensionFragDepth ? '#extension GL_EXT_frag_depth : enable' : '', ( parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ) ? '#extension GL_EXT_draw_buffers : require' : '', ( parameters.extensionShaderTextureLOD || parameters.envMap ) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : '' ]; return chunks.filter( filterEmptyLine ).join( '\n' ); } function generateDefines( defines ) { var chunks = []; for ( var name in defines ) { var value = defines[ name ]; if ( value === false ) { continue; } chunks.push( '#define ' + name + ' ' + value ); } return chunks.join( '\n' ); } function fetchAttributeLocations( gl, program ) { var attributes = {}; var n = gl.getProgramParameter( program, 35721 ); for ( var i = 0; i < n; i ++ ) { var info = gl.getActiveAttrib( program, i ); var name = info.name; // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i ); attributes[ name ] = gl.getAttribLocation( program, name ); } return attributes; } function filterEmptyLine( string ) { return string !== ''; } function replaceLightNums( string, parameters ) { return string .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights ) .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights ) .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights ) .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights ) .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights ) .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows ) .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows ) .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows ); } function replaceClippingPlaneNums( string, parameters ) { return string .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes ) .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) ); } // Resolve Includes var includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm; function resolveIncludes( string ) { return string.replace( includePattern, includeReplacer ); } function includeReplacer( match, include ) { var string = ShaderChunk[ include ]; if ( string === undefined ) { throw new Error( 'Can not resolve #include <' + include + '>' ); } return resolveIncludes( string ); } // Unroll Loops var loopPattern = /#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g; function unrollLoops( string ) { return string.replace( loopPattern, loopReplacer ); } function loopReplacer( match, start, end, snippet ) { var string = ''; for ( var i = parseInt( start ); i < parseInt( end ); i ++ ) { string += snippet .replace( /\[ i \]/g, '[ ' + i + ' ]' ) .replace( /UNROLLED_LOOP_INDEX/g, i ); } return string; } // function generatePrecision( parameters ) { var precisionstring = "precision " + parameters.precision + " float;\nprecision " + parameters.precision + " int;"; if ( parameters.precision === "highp" ) { precisionstring += "\n#define HIGH_PRECISION"; } else if ( parameters.precision === "mediump" ) { precisionstring += "\n#define MEDIUM_PRECISION"; } else if ( parameters.precision === "lowp" ) { precisionstring += "\n#define LOW_PRECISION"; } return precisionstring; } function generateShadowMapTypeDefine( parameters ) { var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC'; if ( parameters.shadowMapType === PCFShadowMap ) { shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF'; } else if ( parameters.shadowMapType === PCFSoftShadowMap ) { shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT'; } else if ( parameters.shadowMapType === VSMShadowMap ) { shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM'; } return shadowMapTypeDefine; } function generateEnvMapTypeDefine( parameters ) { var envMapTypeDefine = 'ENVMAP_TYPE_CUBE'; if ( parameters.envMap ) { switch ( parameters.envMapMode ) { case CubeReflectionMapping: case CubeRefractionMapping: envMapTypeDefine = 'ENVMAP_TYPE_CUBE'; break; case CubeUVReflectionMapping: case CubeUVRefractionMapping: envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV'; break; case EquirectangularReflectionMapping: case EquirectangularRefractionMapping: envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC'; break; case SphericalReflectionMapping: envMapTypeDefine = 'ENVMAP_TYPE_SPHERE'; break; } } return envMapTypeDefine; } function generateEnvMapModeDefine( parameters ) { var envMapModeDefine = 'ENVMAP_MODE_REFLECTION'; if ( parameters.envMap ) { switch ( parameters.envMapMode ) { case CubeRefractionMapping: case EquirectangularRefractionMapping: envMapModeDefine = 'ENVMAP_MODE_REFRACTION'; break; } } return envMapModeDefine; } function generateEnvMapBlendingDefine( parameters ) { var envMapBlendingDefine = 'ENVMAP_BLENDING_NONE'; if ( parameters.envMap ) { switch ( parameters.combine ) { case MultiplyOperation: envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY'; break; case MixOperation: envMapBlendingDefine = 'ENVMAP_BLENDING_MIX'; break; case AddOperation: envMapBlendingDefine = 'ENVMAP_BLENDING_ADD'; break; } } return envMapBlendingDefine; } function WebGLProgram( renderer, cacheKey, parameters ) { var gl = renderer.getContext(); var defines = parameters.defines; var vertexShader = parameters.vertexShader; var fragmentShader = parameters.fragmentShader; var shadowMapTypeDefine = generateShadowMapTypeDefine( parameters ); var envMapTypeDefine = generateEnvMapTypeDefine( parameters ); var envMapModeDefine = generateEnvMapModeDefine( parameters ); var envMapBlendingDefine = generateEnvMapBlendingDefine( parameters ); var gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0; var customExtensions = parameters.isWebGL2 ? '' : generateExtensions( parameters ); var customDefines = generateDefines( defines ); var program = gl.createProgram(); var prefixVertex, prefixFragment; var numMultiviewViews = parameters.numMultiviewViews; if ( parameters.isRawShaderMaterial ) { prefixVertex = [ customDefines ].filter( filterEmptyLine ).join( '\n' ); if ( prefixVertex.length > 0 ) { prefixVertex += '\n'; } prefixFragment = [ customExtensions, customDefines ].filter( filterEmptyLine ).join( '\n' ); if ( prefixFragment.length > 0 ) { prefixFragment += '\n'; } } else { prefixVertex = [ generatePrecision( parameters ), '#define SHADER_NAME ' + parameters.shaderName, customDefines, parameters.instancing ? '#define USE_INSTANCING' : '', parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '', '#define GAMMA_FACTOR ' + gammaFactorDefine, '#define MAX_BONES ' + parameters.maxBones, ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '', ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '', parameters.map ? '#define USE_MAP' : '', parameters.envMap ? '#define USE_ENVMAP' : '', parameters.envMap ? '#define ' + envMapModeDefine : '', parameters.lightMap ? '#define USE_LIGHTMAP' : '', parameters.aoMap ? '#define USE_AOMAP' : '', parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', parameters.bumpMap ? '#define USE_BUMPMAP' : '', parameters.normalMap ? '#define USE_NORMALMAP' : '', ( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '', ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '', parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '', parameters.specularMap ? '#define USE_SPECULARMAP' : '', parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', parameters.alphaMap ? '#define USE_ALPHAMAP' : '', parameters.vertexTangents ? '#define USE_TANGENT' : '', parameters.vertexColors ? '#define USE_COLOR' : '', parameters.vertexUvs ? '#define USE_UV' : '', parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '', parameters.flatShading ? '#define FLAT_SHADED' : '', parameters.skinning ? '#define USE_SKINNING' : '', parameters.useVertexTexture ? '#define BONE_TEXTURE' : '', parameters.morphTargets ? '#define USE_MORPHTARGETS' : '', parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '', parameters.doubleSided ? '#define DOUBLE_SIDED' : '', parameters.flipSided ? '#define FLIP_SIDED' : '', parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '', parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '', 'uniform mat4 modelMatrix;', 'uniform mat4 modelViewMatrix;', 'uniform mat4 projectionMatrix;', 'uniform mat4 viewMatrix;', 'uniform mat3 normalMatrix;', 'uniform vec3 cameraPosition;', 'uniform bool isOrthographic;', '#ifdef USE_INSTANCING', ' attribute mat4 instanceMatrix;', '#endif', 'attribute vec3 position;', 'attribute vec3 normal;', 'attribute vec2 uv;', '#ifdef USE_TANGENT', ' attribute vec4 tangent;', '#endif', '#ifdef USE_COLOR', ' attribute vec3 color;', '#endif', '#ifdef USE_MORPHTARGETS', ' attribute vec3 morphTarget0;', ' attribute vec3 morphTarget1;', ' attribute vec3 morphTarget2;', ' attribute vec3 morphTarget3;', ' #ifdef USE_MORPHNORMALS', ' attribute vec3 morphNormal0;', ' attribute vec3 morphNormal1;', ' attribute vec3 morphNormal2;', ' attribute vec3 morphNormal3;', ' #else', ' attribute vec3 morphTarget4;', ' attribute vec3 morphTarget5;', ' attribute vec3 morphTarget6;', ' attribute vec3 morphTarget7;', ' #endif', '#endif', '#ifdef USE_SKINNING', ' attribute vec4 skinIndex;', ' attribute vec4 skinWeight;', '#endif', '\n' ].filter( filterEmptyLine ).join( '\n' ); prefixFragment = [ customExtensions, generatePrecision( parameters ), '#define SHADER_NAME ' + parameters.shaderName, customDefines, parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest + ( parameters.alphaTest % 1 ? '' : '.0' ) : '', // add '.0' if integer '#define GAMMA_FACTOR ' + gammaFactorDefine, ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '', ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '', parameters.map ? '#define USE_MAP' : '', parameters.matcap ? '#define USE_MATCAP' : '', parameters.envMap ? '#define USE_ENVMAP' : '', parameters.envMap ? '#define ' + envMapTypeDefine : '', parameters.envMap ? '#define ' + envMapModeDefine : '', parameters.envMap ? '#define ' + envMapBlendingDefine : '', parameters.lightMap ? '#define USE_LIGHTMAP' : '', parameters.aoMap ? '#define USE_AOMAP' : '', parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', parameters.bumpMap ? '#define USE_BUMPMAP' : '', parameters.normalMap ? '#define USE_NORMALMAP' : '', ( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '', ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '', parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', parameters.specularMap ? '#define USE_SPECULARMAP' : '', parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', parameters.alphaMap ? '#define USE_ALPHAMAP' : '', parameters.sheen ? '#define USE_SHEEN' : '', parameters.vertexTangents ? '#define USE_TANGENT' : '', parameters.vertexColors ? '#define USE_COLOR' : '', parameters.vertexUvs ? '#define USE_UV' : '', parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '', parameters.gradientMap ? '#define USE_GRADIENTMAP' : '', parameters.flatShading ? '#define FLAT_SHADED' : '', parameters.doubleSided ? '#define DOUBLE_SIDED' : '', parameters.flipSided ? '#define FLIP_SIDED' : '', parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '', parameters.physicallyCorrectLights ? '#define PHYSICALLY_CORRECT_LIGHTS' : '', parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '', ( ( parameters.extensionShaderTextureLOD || parameters.envMap ) && parameters.rendererExtensionShaderTextureLod ) ? '#define TEXTURE_LOD_EXT' : '', 'uniform mat4 viewMatrix;', 'uniform vec3 cameraPosition;', 'uniform bool isOrthographic;', ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '', ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '', parameters.dithering ? '#define DITHERING' : '', ( parameters.outputEncoding || parameters.mapEncoding || parameters.matcapEncoding || parameters.envMapEncoding || parameters.emissiveMapEncoding || parameters.lightMapEncoding ) ? ShaderChunk[ 'encodings_pars_fragment' ] : '', // this code is required here because it is used by the various encoding/decoding function defined below parameters.mapEncoding ? getTexelDecodingFunction( 'mapTexelToLinear', parameters.mapEncoding ) : '', parameters.matcapEncoding ? getTexelDecodingFunction( 'matcapTexelToLinear', parameters.matcapEncoding ) : '', parameters.envMapEncoding ? getTexelDecodingFunction( 'envMapTexelToLinear', parameters.envMapEncoding ) : '', parameters.emissiveMapEncoding ? getTexelDecodingFunction( 'emissiveMapTexelToLinear', parameters.emissiveMapEncoding ) : '', parameters.lightMapEncoding ? getTexelDecodingFunction( 'lightMapTexelToLinear', parameters.lightMapEncoding ) : '', parameters.outputEncoding ? getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputEncoding ) : '', parameters.depthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '', '\n' ].filter( filterEmptyLine ).join( '\n' ); } vertexShader = resolveIncludes( vertexShader ); vertexShader = replaceLightNums( vertexShader, parameters ); vertexShader = replaceClippingPlaneNums( vertexShader, parameters ); fragmentShader = resolveIncludes( fragmentShader ); fragmentShader = replaceLightNums( fragmentShader, parameters ); fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters ); vertexShader = unrollLoops( vertexShader ); fragmentShader = unrollLoops( fragmentShader ); if ( parameters.isWebGL2 && ! parameters.isRawShaderMaterial ) { var isGLSL3ShaderMaterial = false; var versionRegex = /^\s*#version\s+300\s+es\s*\n/; if ( parameters.isShaderMaterial && vertexShader.match( versionRegex ) !== null && fragmentShader.match( versionRegex ) !== null ) { isGLSL3ShaderMaterial = true; vertexShader = vertexShader.replace( versionRegex, '' ); fragmentShader = fragmentShader.replace( versionRegex, '' ); } // GLSL 3.0 conversion prefixVertex = [ '#version 300 es\n', '#define attribute in', '#define varying out', '#define texture2D texture' ].join( '\n' ) + '\n' + prefixVertex; prefixFragment = [ '#version 300 es\n', '#define varying in', isGLSL3ShaderMaterial ? '' : 'out highp vec4 pc_fragColor;', isGLSL3ShaderMaterial ? '' : '#define gl_FragColor pc_fragColor', '#define gl_FragDepthEXT gl_FragDepth', '#define texture2D texture', '#define textureCube texture', '#define texture2DProj textureProj', '#define texture2DLodEXT textureLod', '#define texture2DProjLodEXT textureProjLod', '#define textureCubeLodEXT textureLod', '#define texture2DGradEXT textureGrad', '#define texture2DProjGradEXT textureProjGrad', '#define textureCubeGradEXT textureGrad' ].join( '\n' ) + '\n' + prefixFragment; // Multiview if ( numMultiviewViews > 0 ) { prefixVertex = prefixVertex.replace( '#version 300 es\n', [ '#version 300 es\n', '#extension GL_OVR_multiview2 : require', 'layout(num_views = ' + numMultiviewViews + ') in;', '#define VIEW_ID gl_ViewID_OVR' ].join( '\n' ) ); prefixVertex = prefixVertex.replace( [ 'uniform mat4 modelViewMatrix;', 'uniform mat4 projectionMatrix;', 'uniform mat4 viewMatrix;', 'uniform mat3 normalMatrix;' ].join( '\n' ), [ 'uniform mat4 modelViewMatrices[' + numMultiviewViews + '];', 'uniform mat4 projectionMatrices[' + numMultiviewViews + '];', 'uniform mat4 viewMatrices[' + numMultiviewViews + '];', 'uniform mat3 normalMatrices[' + numMultiviewViews + '];', '#define modelViewMatrix modelViewMatrices[VIEW_ID]', '#define projectionMatrix projectionMatrices[VIEW_ID]', '#define viewMatrix viewMatrices[VIEW_ID]', '#define normalMatrix normalMatrices[VIEW_ID]' ].join( '\n' ) ); prefixFragment = prefixFragment.replace( '#version 300 es\n', [ '#version 300 es\n', '#extension GL_OVR_multiview2 : require', '#define VIEW_ID gl_ViewID_OVR' ].join( '\n' ) ); prefixFragment = prefixFragment.replace( 'uniform mat4 viewMatrix;', [ 'uniform mat4 viewMatrices[' + numMultiviewViews + '];', '#define viewMatrix viewMatrices[VIEW_ID]' ].join( '\n' ) ); } } var vertexGlsl = prefixVertex + vertexShader; var fragmentGlsl = prefixFragment + fragmentShader; // console.log( '*VERTEX*', vertexGlsl ); // console.log( '*FRAGMENT*', fragmentGlsl ); var glVertexShader = WebGLShader( gl, 35633, vertexGlsl ); var glFragmentShader = WebGLShader( gl, 35632, fragmentGlsl ); gl.attachShader( program, glVertexShader ); gl.attachShader( program, glFragmentShader ); // Force a particular attribute to index 0. if ( parameters.index0AttributeName !== undefined ) { gl.bindAttribLocation( program, 0, parameters.index0AttributeName ); } else if ( parameters.morphTargets === true ) { // programs with morphTargets displace position out of attribute 0 gl.bindAttribLocation( program, 0, 'position' ); } gl.linkProgram( program ); // check for link errors if ( renderer.debug.checkShaderErrors ) { var programLog = gl.getProgramInfoLog( program ).trim(); var vertexLog = gl.getShaderInfoLog( glVertexShader ).trim(); var fragmentLog = gl.getShaderInfoLog( glFragmentShader ).trim(); var runnable = true; var haveDiagnostics = true; if ( gl.getProgramParameter( program, 35714 ) === false ) { runnable = false; var vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' ); var fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' ); console.error( 'THREE.WebGLProgram: shader error: ', gl.getError(), '35715', gl.getProgramParameter( program, 35715 ), 'gl.getProgramInfoLog', programLog, vertexErrors, fragmentErrors ); } else if ( programLog !== '' ) { console.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()', programLog ); } else if ( vertexLog === '' || fragmentLog === '' ) { haveDiagnostics = false; } if ( haveDiagnostics ) { this.diagnostics = { runnable: runnable, programLog: programLog, vertexShader: { log: vertexLog, prefix: prefixVertex }, fragmentShader: { log: fragmentLog, prefix: prefixFragment } }; } } // clean up gl.deleteShader( glVertexShader ); gl.deleteShader( glFragmentShader ); // set up caching for uniform locations var cachedUniforms; this.getUniforms = function () { if ( cachedUniforms === undefined ) { cachedUniforms = new WebGLUniforms( gl, program ); } return cachedUniforms; }; // set up caching for attribute locations var cachedAttributes; this.getAttributes = function () { if ( cachedAttributes === undefined ) { cachedAttributes = fetchAttributeLocations( gl, program ); } return cachedAttributes; }; // free resource this.destroy = function () { gl.deleteProgram( program ); this.program = undefined; }; // this.name = parameters.shaderName; this.id = programIdCount ++; this.cacheKey = cacheKey; this.usedTimes = 1; this.program = program; this.vertexShader = glVertexShader; this.fragmentShader = glFragmentShader; this.numMultiviewViews = numMultiviewViews; return this; } /** * @author mrdoob / http://mrdoob.com/ */ function WebGLPrograms( renderer, extensions, capabilities ) { var programs = []; var isWebGL2 = capabilities.isWebGL2; var logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer; var floatVertexTextures = capabilities.floatVertexTextures; var precision = capabilities.precision; var maxVertexUniforms = capabilities.maxVertexUniforms; var vertexTextures = capabilities.vertexTextures; var shaderIDs = { MeshDepthMaterial: 'depth', MeshDistanceMaterial: 'distanceRGBA', MeshNormalMaterial: 'normal', MeshBasicMaterial: 'basic', MeshLambertMaterial: 'lambert', MeshPhongMaterial: 'phong', MeshToonMaterial: 'toon', MeshStandardMaterial: 'physical', MeshPhysicalMaterial: 'physical', MeshMatcapMaterial: 'matcap', LineBasicMaterial: 'basic', LineDashedMaterial: 'dashed', PointsMaterial: 'points', ShadowMaterial: 'shadow', SpriteMaterial: 'sprite' }; var parameterNames = [ "precision", "isWebGL2", "supportsVertexTextures", "outputEncoding", "instancing", "numMultiviewViews", "map", "mapEncoding", "matcap", "matcapEncoding", "envMap", "envMapMode", "envMapEncoding", "envMapCubeUV", "lightMap", "lightMapEncoding", "aoMap", "emissiveMap", "emissiveMapEncoding", "bumpMap", "normalMap", "objectSpaceNormalMap", "tangentSpaceNormalMap", "clearcoatNormalMap", "displacementMap", "specularMap", "roughnessMap", "metalnessMap", "gradientMap", "alphaMap", "combine", "vertexColors", "vertexTangents", "vertexUvs", "uvsVertexOnly", "fog", "useFog", "fogExp2", "flatShading", "sizeAttenuation", "logarithmicDepthBuffer", "skinning", "maxBones", "useVertexTexture", "morphTargets", "morphNormals", "maxMorphTargets", "maxMorphNormals", "premultipliedAlpha", "numDirLights", "numPointLights", "numSpotLights", "numHemiLights", "numRectAreaLights", "numDirLightShadows", "numPointLightShadows", "numSpotLightShadows", "shadowMapEnabled", "shadowMapType", "toneMapping", 'physicallyCorrectLights', "alphaTest", "doubleSided", "flipSided", "numClippingPlanes", "numClipIntersection", "depthPacking", "dithering", "sheen" ]; function getShaderObject( material, shaderID ) { var shaderobject; if ( shaderID ) { var shader = ShaderLib[ shaderID ]; shaderobject = { name: material.type, uniforms: UniformsUtils.clone( shader.uniforms ), vertexShader: shader.vertexShader, fragmentShader: shader.fragmentShader }; } else { shaderobject = { name: material.type, uniforms: material.uniforms, vertexShader: material.vertexShader, fragmentShader: material.fragmentShader }; } return shaderobject; } function allocateBones( object ) { var skeleton = object.skeleton; var bones = skeleton.bones; if ( floatVertexTextures ) { return 1024; } else { // default for when object is not specified // ( for example when prebuilding shader to be used with multiple objects ) // // - leave some extra space for other uniforms // - limit here is ANGLE's 254 max uniform vectors // (up to 54 should be safe) var nVertexUniforms = maxVertexUniforms; var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 ); var maxBones = Math.min( nVertexMatrices, bones.length ); if ( maxBones < bones.length ) { console.warn( 'THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.' ); return 0; } return maxBones; } } function getTextureEncodingFromMap( map ) { var encoding; if ( ! map ) { encoding = LinearEncoding; } else if ( map.isTexture ) { encoding = map.encoding; } else if ( map.isWebGLRenderTarget ) { console.warn( "THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead." ); encoding = map.texture.encoding; } return encoding; } this.getParameters = function ( material, lights, shadows, scene, nClipPlanes, nClipIntersection, object ) { var fog = scene.fog; var environment = material.isMeshStandardMaterial ? scene.environment : null; var envMap = material.envMap || environment; var shaderID = shaderIDs[ material.type ]; // heuristics to create shader parameters according to lights in the scene // (not to blow over maxLights budget) var maxBones = object.isSkinnedMesh ? allocateBones( object ) : 0; if ( material.precision !== null ) { precision = capabilities.getMaxPrecision( material.precision ); if ( precision !== material.precision ) { console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' ); } } var shaderobject = getShaderObject( material, shaderID ); material.onBeforeCompile( shaderobject, renderer ); var currentRenderTarget = renderer.getRenderTarget(); var numMultiviewViews = currentRenderTarget && currentRenderTarget.isWebGLMultiviewRenderTarget ? currentRenderTarget.numViews : 0; var parameters = { isWebGL2: isWebGL2, shaderID: shaderID, shaderName: shaderobject.name, uniforms: shaderobject.uniforms, vertexShader: shaderobject.vertexShader, fragmentShader: shaderobject.fragmentShader, defines: material.defines, isRawShaderMaterial: material.isRawShaderMaterial, isShaderMaterial: material.isShaderMaterial, precision: precision, instancing: object.isInstancedMesh === true, supportsVertexTextures: vertexTextures, numMultiviewViews: numMultiviewViews, outputEncoding: ( currentRenderTarget !== null ) ? getTextureEncodingFromMap( currentRenderTarget.texture ) : renderer.outputEncoding, map: !! material.map, mapEncoding: getTextureEncodingFromMap( material.map ), matcap: !! material.matcap, matcapEncoding: getTextureEncodingFromMap( material.matcap ), envMap: !! envMap, envMapMode: envMap && envMap.mapping, envMapEncoding: getTextureEncodingFromMap( envMap ), envMapCubeUV: ( !! envMap ) && ( ( envMap.mapping === CubeUVReflectionMapping ) || ( envMap.mapping === CubeUVRefractionMapping ) ), lightMap: !! material.lightMap, lightMapEncoding: getTextureEncodingFromMap( material.lightMap ), aoMap: !! material.aoMap, emissiveMap: !! material.emissiveMap, emissiveMapEncoding: getTextureEncodingFromMap( material.emissiveMap ), bumpMap: !! material.bumpMap, normalMap: !! material.normalMap, objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap, tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap, clearcoatNormalMap: !! material.clearcoatNormalMap, displacementMap: !! material.displacementMap, roughnessMap: !! material.roughnessMap, metalnessMap: !! material.metalnessMap, specularMap: !! material.specularMap, alphaMap: !! material.alphaMap, gradientMap: !! material.gradientMap, sheen: !! material.sheen, combine: material.combine, vertexTangents: ( material.normalMap && material.vertexTangents ), vertexColors: material.vertexColors, vertexUvs: !! material.map || !! material.bumpMap || !! material.normalMap || !! material.specularMap || !! material.alphaMap || !! material.emissiveMap || !! material.roughnessMap || !! material.metalnessMap || !! material.clearcoatNormalMap || !! material.displacementMap, uvsVertexOnly: ! ( !! material.map || !! material.bumpMap || !! material.normalMap || !! material.specularMap || !! material.alphaMap || !! material.emissiveMap || !! material.roughnessMap || !! material.metalnessMap || !! material.clearcoatNormalMap ) && !! material.displacementMap, fog: !! fog, useFog: material.fog, fogExp2: ( fog && fog.isFogExp2 ), flatShading: material.flatShading, sizeAttenuation: material.sizeAttenuation, logarithmicDepthBuffer: logarithmicDepthBuffer, skinning: material.skinning && maxBones > 0, maxBones: maxBones, useVertexTexture: floatVertexTextures, morphTargets: material.morphTargets, morphNormals: material.morphNormals, maxMorphTargets: renderer.maxMorphTargets, maxMorphNormals: renderer.maxMorphNormals, numDirLights: lights.directional.length, numPointLights: lights.point.length, numSpotLights: lights.spot.length, numRectAreaLights: lights.rectArea.length, numHemiLights: lights.hemi.length, numDirLightShadows: lights.directionalShadowMap.length, numPointLightShadows: lights.pointShadowMap.length, numSpotLightShadows: lights.spotShadowMap.length, numClippingPlanes: nClipPlanes, numClipIntersection: nClipIntersection, dithering: material.dithering, shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0, shadowMapType: renderer.shadowMap.type, toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping, physicallyCorrectLights: renderer.physicallyCorrectLights, premultipliedAlpha: material.premultipliedAlpha, alphaTest: material.alphaTest, doubleSided: material.side === DoubleSide, flipSided: material.side === BackSide, depthPacking: ( material.depthPacking !== undefined ) ? material.depthPacking : false, index0AttributeName: material.index0AttributeName, extensionDerivatives: material.extensions && material.extensions.derivatives, extensionFragDepth: material.extensions && material.extensions.frawbuffers, extensionDrawbuffers: material.extensions && material.extensions.drawbuffers, extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD, rendererExtensionFragDepth: isWebGL2 || extensions.get( 'EXT_frag_depth' ) !== null, rendererExtensionDrawBuffers: isWebGL2 || extensions.get( 'WEBGL_draw_buffers' ) !== null, rendererExtensionShaderTextureLod: isWebGL2 || extensions.get( 'EXT_shader_texture_lod' ) !== null, onBeforeCompile: material.onBeforeCompile }; return parameters; }; this.getProgramCacheKey = function ( parameters ) { var array = []; if ( parameters.shaderID ) { array.push( parameters.shaderID ); } else { array.push( parameters.fragmentShader ); array.push( parameters.vertexShader ); } if ( parameters.defines !== undefined ) { for ( var name in parameters.defines ) { array.push( name ); array.push( parameters.defines[ name ] ); } } if ( parameters.isRawShaderMaterial === undefined ) { for ( var i = 0; i < parameterNames.length; i ++ ) { array.push( parameters[ parameterNames[ i ] ] ); } array.push( renderer.outputEncoding ); array.push( renderer.gammaFactor ); } array.push( parameters.onBeforeCompile.toString() ); return array.join(); }; this.acquireProgram = function ( parameters, cacheKey ) { var program; // Check if code has been already compiled for ( var p = 0, pl = programs.length; p < pl; p ++ ) { var preexistingProgram = programs[ p ]; if ( preexistingProgram.cacheKey === cacheKey ) { program = preexistingProgram; ++ program.usedTimes; break; } } if ( program === undefined ) { program = new WebGLProgram( renderer, cacheKey, parameters ); programs.push( program ); } return program; }; this.releaseProgram = function ( program ) { if ( -- program.usedTimes === 0 ) { // Remove from unordered set var i = programs.indexOf( program ); programs[ i ] = programs[ programs.length - 1 ]; programs.pop(); // Free WebGL resources program.destroy(); } }; // Exposed for resource monitoring & error feedback via renderer.info: this.programs = programs; } /** * @author fordacious / fordacious.github.io */ function WebGLProperties() { var properties = new WeakMap(); function get( object ) { var map = properties.get( object ); if ( map === undefined ) { map = {}; properties.set( object, map ); } return map; } function remove( object ) { properties.delete( object ); } function update( object, key, value ) { properties.get( object )[ key ] = value; } function dispose() { properties = new WeakMap(); } return { get: get, remove: remove, update: update, dispose: dispose }; } /** * @author mrdoob / http://mrdoob.com/ */ function painterSortStable( a, b ) { if ( a.groupOrder !== b.groupOrder ) { return a.groupOrder - b.groupOrder; } else if ( a.renderOrder !== b.renderOrder ) { return a.renderOrder - b.renderOrder; } else if ( a.program !== b.program ) { return a.program.id - b.program.id; } else if ( a.material.id !== b.material.id ) { return a.material.id - b.material.id; } else if ( a.z !== b.z ) { return a.z - b.z; } else { return a.id - b.id; } } function reversePainterSortStable( a, b ) { if ( a.groupOrder !== b.groupOrder ) { return a.groupOrder - b.groupOrder; } else if ( a.renderOrder !== b.renderOrder ) { return a.renderOrder - b.renderOrder; } else if ( a.z !== b.z ) { return b.z - a.z; } else { return a.id - b.id; } } function WebGLRenderList() { var renderItems = []; var renderItemsIndex = 0; var opaque = []; var transparent = []; var defaultProgram = { id: - 1 }; function init() { renderItemsIndex = 0; opaque.length = 0; transparent.length = 0; } function getNextRenderItem( object, geometry, material, groupOrder, z, group ) { var renderItem = renderItems[ renderItemsIndex ]; if ( renderItem === undefined ) { renderItem = { id: object.id, object: object, geometry: geometry, material: material, program: material.program || defaultProgram, groupOrder: groupOrder, renderOrder: object.renderOrder, z: z, group: group }; renderItems[ renderItemsIndex ] = renderItem; } else { renderItem.id = object.id; renderItem.object = object; renderItem.geometry = geometry; renderItem.material = material; renderItem.program = material.program || defaultProgram; renderItem.groupOrder = groupOrder; renderItem.renderOrder = object.renderOrder; renderItem.z = z; renderItem.group = group; } renderItemsIndex ++; return renderItem; } function push( object, geometry, material, groupOrder, z, group ) { var renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group ); ( material.transparent === true ? transparent : opaque ).push( renderItem ); } function unshift( object, geometry, material, groupOrder, z, group ) { var renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group ); ( material.transparent === true ? transparent : opaque ).unshift( renderItem ); } function sort( customOpaqueSort, customTransparentSort ) { if ( opaque.length > 1 ) { opaque.sort( customOpaqueSort || painterSortStable ); } if ( transparent.length > 1 ) { transparent.sort( customTransparentSort || reversePainterSortStable ); } } return { opaque: opaque, transparent: transparent, init: init, push: push, unshift: unshift, sort: sort }; } function WebGLRenderLists() { var lists = new WeakMap(); function onSceneDispose( event ) { var scene = event.target; scene.removeEventListener( 'dispose', onSceneDispose ); lists.delete( scene ); } function get( scene, camera ) { var cameras = lists.get( scene ); var list; if ( cameras === undefined ) { list = new WebGLRenderList(); lists.set( scene, new WeakMap() ); lists.get( scene ).set( camera, list ); scene.addEventListener( 'dispose', onSceneDispose ); } else { list = cameras.get( camera ); if ( list === undefined ) { list = new WebGLRenderList(); cameras.set( camera, list ); } } return list; } function dispose() { lists = new WeakMap(); } return { get: get, dispose: dispose }; } /** * @author mrdoob / http://mrdoob.com/ */ function UniformsCache() { var lights = {}; return { get: function ( light ) { if ( lights[ light.id ] !== undefined ) { return lights[ light.id ]; } var uniforms; switch ( light.type ) { case 'DirectionalLight': uniforms = { direction: new Vector3(), color: new Color(), shadow: false, shadowBias: 0, shadowRadius: 1, shadowMapSize: new Vector2() }; break; case 'SpotLight': uniforms = { position: new Vector3(), direction: new Vector3(), color: new Color(), distance: 0, coneCos: 0, penumbraCos: 0, decay: 0, shadow: false, shadowBias: 0, shadowRadius: 1, shadowMapSize: new Vector2() }; break; case 'PointLight': uniforms = { position: new Vector3(), color: new Color(), distance: 0, decay: 0, shadow: false, shadowBias: 0, shadowRadius: 1, shadowMapSize: new Vector2(), shadowCameraNear: 1, shadowCameraFar: 1000 }; break; case 'HemisphereLight': uniforms = { direction: new Vector3(), skyColor: new Color(), groundColor: new Color() }; break; case 'RectAreaLight': uniforms = { color: new Color(), position: new Vector3(), halfWidth: new Vector3(), halfHeight: new Vector3() // TODO (abelnation): set RectAreaLight shadow uniforms }; break; } lights[ light.id ] = uniforms; return uniforms; } }; } var nextVersion = 0; function shadowCastingLightsFirst( lightA, lightB ) { return ( lightB.castShadow ? 1 : 0 ) - ( lightA.castShadow ? 1 : 0 ); } function WebGLLights() { var cache = new UniformsCache(); var state = { version: 0, hash: { directionalLength: - 1, pointLength: - 1, spotLength: - 1, rectAreaLength: - 1, hemiLength: - 1, numDirectionalShadows: - 1, numPointShadows: - 1, numSpotShadows: - 1, }, ambient: [ 0, 0, 0 ], probe: [], directional: [], directionalShadowMap: [], directionalShadowMatrix: [], spot: [], spotShadowMap: [], spotShadowMatrix: [], rectArea: [], point: [], pointShadowMap: [], pointShadowMatrix: [], hemi: [], numDirectionalShadows: - 1, numPointShadows: - 1, numSpotShadows: - 1 }; for ( var i = 0; i < 9; i ++ ) { state.probe.push( new Vector3() ); } var vector3 = new Vector3(); var matrix4 = new Matrix4(); var matrix42 = new Matrix4(); function setup( lights, shadows, camera ) { var r = 0, g = 0, b = 0; for ( var i = 0; i < 9; i ++ ) { state.probe[ i ].set( 0, 0, 0 ); } var directionalLength = 0; var pointLength = 0; var spotLength = 0; var rectAreaLength = 0; var hemiLength = 0; var numDirectionalShadows = 0; var numPointShadows = 0; var numSpotShadows = 0; var viewMatrix = camera.matrixWorldInverse; lights.sort( shadowCastingLightsFirst ); for ( var i = 0, l = lights.length; i < l; i ++ ) { var light = lights[ i ]; var color = light.color; var intensity = light.intensity; var distance = light.distance; var shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null; if ( light.isAmbientLight ) { r += color.r * intensity; g += color.g * intensity; b += color.b * intensity; } else if ( light.isLightProbe ) { for ( var j = 0; j < 9; j ++ ) { state.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity ); } } else if ( light.isDirectionalLight ) { var uniforms = cache.get( light ); uniforms.color.copy( light.color ).multiplyScalar( light.intensity ); uniforms.direction.setFromMatrixPosition( light.matrixWorld ); vector3.setFromMatrixPosition( light.target.matrixWorld ); uniforms.direction.sub( vector3 ); uniforms.direction.transformDirection( viewMatrix ); uniforms.shadow = light.castShadow; if ( light.castShadow ) { var shadow = light.shadow; uniforms.shadowBias = shadow.bias; uniforms.shadowRadius = shadow.radius; uniforms.shadowMapSize = shadow.mapSize; state.directionalShadowMap[ directionalLength ] = shadowMap; state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix; numDirectionalShadows ++; } state.directional[ directionalLength ] = uniforms; directionalLength ++; } else if ( light.isSpotLight ) { var uniforms = cache.get( light ); uniforms.position.setFromMatrixPosition( light.matrixWorld ); uniforms.position.applyMatrix4( viewMatrix ); uniforms.color.copy( color ).multiplyScalar( intensity ); uniforms.distance = distance; uniforms.direction.setFromMatrixPosition( light.matrixWorld ); vector3.setFromMatrixPosition( light.target.matrixWorld ); uniforms.direction.sub( vector3 ); uniforms.direction.transformDirection( viewMatrix ); uniforms.coneCos = Math.cos( light.angle ); uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) ); uniforms.decay = light.decay; uniforms.shadow = light.castShadow; if ( light.castShadow ) { var shadow = light.shadow; uniforms.shadowBias = shadow.bias; uniforms.shadowRadius = shadow.radius; uniforms.shadowMapSize = shadow.mapSize; state.spotShadowMap[ spotLength ] = shadowMap; state.spotShadowMatrix[ spotLength ] = light.shadow.matrix; numSpotShadows ++; } state.spot[ spotLength ] = uniforms; spotLength ++; } else if ( light.isRectAreaLight ) { var uniforms = cache.get( light ); // (a) intensity is the total visible light emitted //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) ); // (b) intensity is the brightness of the light uniforms.color.copy( color ).multiplyScalar( intensity ); uniforms.position.setFromMatrixPosition( light.matrixWorld ); uniforms.position.applyMatrix4( viewMatrix ); // extract local rotation of light to derive width/height half vectors matrix42.identity(); matrix4.copy( light.matrixWorld ); matrix4.premultiply( viewMatrix ); matrix42.extractRotation( matrix4 ); uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 ); uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 ); uniforms.halfWidth.applyMatrix4( matrix42 ); uniforms.halfHeight.applyMatrix4( matrix42 ); // TODO (abelnation): RectAreaLight distance? // uniforms.distance = distance; state.rectArea[ rectAreaLength ] = uniforms; rectAreaLength ++; } else if ( light.isPointLight ) { var uniforms = cache.get( light ); uniforms.position.setFromMatrixPosition( light.matrixWorld ); uniforms.position.applyMatrix4( viewMatrix ); uniforms.color.copy( light.color ).multiplyScalar( light.intensity ); uniforms.distance = light.distance; uniforms.decay = light.decay; uniforms.shadow = light.castShadow; if ( light.castShadow ) { var shadow = light.shadow; uniforms.shadowBias = shadow.bias; uniforms.shadowRadius = shadow.radius; uniforms.shadowMapSize = shadow.mapSize; uniforms.shadowCameraNear = shadow.camera.near; uniforms.shadowCameraFar = shadow.camera.far; state.pointShadowMap[ pointLength ] = shadowMap; state.pointShadowMatrix[ pointLength ] = light.shadow.matrix; numPointShadows ++; } state.point[ pointLength ] = uniforms; pointLength ++; } else if ( light.isHemisphereLight ) { var uniforms = cache.get( light ); uniforms.direction.setFromMatrixPosition( light.matrixWorld ); uniforms.direction.transformDirection( viewMatrix ); uniforms.direction.normalize(); uniforms.skyColor.copy( light.color ).multiplyScalar( intensity ); uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity ); state.hemi[ hemiLength ] = uniforms; hemiLength ++; } } state.ambient[ 0 ] = r; state.ambient[ 1 ] = g; state.ambient[ 2 ] = b; var hash = state.hash; if ( hash.directionalLength !== directionalLength || hash.pointLength !== pointLength || hash.spotLength !== spotLength || hash.rectAreaLength !== rectAreaLength || hash.hemiLength !== hemiLength || hash.numDirectionalShadows !== numDirectionalShadows || hash.numPointShadows !== numPointShadows || hash.numSpotShadows !== numSpotShadows ) { state.directional.length = directionalLength; state.spot.length = spotLength; state.rectArea.length = rectAreaLength; state.point.length = pointLength; state.hemi.length = hemiLength; state.directionalShadowMap.length = numDirectionalShadows; state.pointShadowMap.length = numPointShadows; state.spotShadowMap.length = numSpotShadows; state.directionalShadowMatrix.length = numDirectionalShadows; state.pointShadowMatrix.length = numPointShadows; state.spotShadowMatrix.length = numSpotShadows; hash.directionalLength = directionalLength; hash.pointLength = pointLength; hash.spotLength = spotLength; hash.rectAreaLength = rectAreaLength; hash.hemiLength = hemiLength; hash.numDirectionalShadows = numDirectionalShadows; hash.numPointShadows = numPointShadows; hash.numSpotShadows = numSpotShadows; state.version = nextVersion ++; } } return { setup: setup, state: state }; } /** * @author Mugen87 / https://github.com/Mugen87 */ function WebGLRenderState() { var lights = new WebGLLights(); var lightsArray = []; var shadowsArray = []; function init() { lightsArray.length = 0; shadowsArray.length = 0; } function pushLight( light ) { lightsArray.push( light ); } function pushShadow( shadowLight ) { shadowsArray.push( shadowLight ); } function setupLights( camera ) { lights.setup( lightsArray, shadowsArray, camera ); } var state = { lightsArray: lightsArray, shadowsArray: shadowsArray, lights: lights }; return { init: init, state: state, setupLights: setupLights, pushLight: pushLight, pushShadow: pushShadow }; } function WebGLRenderStates() { var renderStates = new WeakMap(); function onSceneDispose( event ) { var scene = event.target; scene.removeEventListener( 'dispose', onSceneDispose ); renderStates.delete( scene ); } function get( scene, camera ) { var renderState; if ( renderStates.has( scene ) === false ) { renderState = new WebGLRenderState(); renderStates.set( scene, new WeakMap() ); renderStates.get( scene ).set( camera, renderState ); scene.addEventListener( 'dispose', onSceneDispose ); } else { if ( renderStates.get( scene ).has( camera ) === false ) { renderState = new WebGLRenderState(); renderStates.get( scene ).set( camera, renderState ); } else { renderState = renderStates.get( scene ).get( camera ); } } return renderState; } function dispose() { renderStates = new WeakMap(); } return { get: get, dispose: dispose }; } /** * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ * @author bhouston / https://clara.io * @author WestLangley / http://github.com/WestLangley * * parameters = { * * opacity: , * * map: new THREE.Texture( ), * * alphaMap: new THREE.Texture( ), * * displacementMap: new THREE.Texture( ), * displacementScale: , * displacementBias: , * * wireframe: , * wireframeLinewidth: * } */ function MeshDepthMaterial( parameters ) { Material.call( this ); this.type = 'MeshDepthMaterial'; this.depthPacking = BasicDepthPacking; this.skinning = false; this.morphTargets = false; this.map = null; this.alphaMap = null; this.displacementMap = null; this.displacementScale = 1; this.displacementBias = 0; this.wireframe = false; this.wireframeLinewidth = 1; this.fog = false; this.setValues( parameters ); } MeshDepthMaterial.prototype = Object.create( Material.prototype ); MeshDepthMaterial.prototype.constructor = MeshDepthMaterial; MeshDepthMaterial.prototype.isMeshDepthMaterial = true; MeshDepthMaterial.prototype.copy = function ( source ) { Material.prototype.copy.call( this, source ); this.depthPacking = source.depthPacking; this.skinning = source.skinning; this.morphTargets = source.morphTargets; this.map = source.map; this.alphaMap = source.alphaMap; this.displacementMap = source.displacementMap; this.displacementScale = source.displacementScale; this.displacementBias = source.displacementBias; this.wireframe = source.wireframe; this.wireframeLinewidth = source.wireframeLinewidth; return this; }; /** * @author WestLangley / http://github.com/WestLangley * * parameters = { * * referencePosition: , * nearDistance: , * farDistance: , * * skinning: , * morphTargets: , * * map: new THREE.Texture( ), * * alphaMap: new THREE.Texture( ), * * displacementMap: new THREE.Texture( ), * displacementScale: , * displacementBias: * * } */ function MeshDistanceMaterial( parameters ) { Material.call( this ); this.type = 'MeshDistanceMaterial'; this.referencePosition = new Vector3(); this.nearDistance = 1; this.farDistance = 1000; this.skinning = false; this.morphTargets = false; this.map = null; this.alphaMap = null; this.displacementMap = null; this.displacementScale = 1; this.displacementBias = 0; this.fog = false; this.setValues( parameters ); } MeshDistanceMaterial.prototype = Object.create( Material.prototype ); MeshDistanceMaterial.prototype.constructor = MeshDistanceMaterial; MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true; MeshDistanceMaterial.prototype.copy = function ( source ) { Material.prototype.copy.call( this, source ); this.referencePosition.copy( source.referencePosition ); this.nearDistance = source.nearDistance; this.farDistance = source.farDistance; this.skinning = source.skinning; this.morphTargets = source.morphTargets; this.map = source.map; this.alphaMap = source.alphaMap; this.displacementMap = source.displacementMap; this.displacementScale = source.displacementScale; this.displacementBias = source.displacementBias; return this; }; var vsm_frag = "uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include \nvoid main() {\n float mean = 0.0;\n float squared_mean = 0.0;\n\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy ) / resolution ) );\n for ( float i = -1.0; i < 1.0 ; i += SAMPLE_RATE) {\n #ifdef HORIZONAL_PASS\n vec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( i, 0.0 ) * radius ) / resolution ) );\n mean += distribution.x;\n squared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n #else\n float depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, i ) * radius ) / resolution ) );\n mean += depth;\n squared_mean += depth * depth;\n #endif\n }\n mean = mean * HALF_SAMPLE_RATE;\n squared_mean = squared_mean * HALF_SAMPLE_RATE;\n float std_dev = sqrt( squared_mean - mean * mean );\n gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}"; var vsm_vert = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}"; /** * @author alteredq / http://alteredqualia.com/ * @author mrdoob / http://mrdoob.com/ */ function WebGLShadowMap( _renderer, _objects, maxTextureSize ) { var _frustum = new Frustum(), _shadowMapSize = new Vector2(), _viewportSize = new Vector2(), _viewport = new Vector4(), _depthMaterials = [], _distanceMaterials = [], _materialCache = {}; var shadowSide = { 0: BackSide, 1: FrontSide, 2: DoubleSide }; var shadowMaterialVertical = new ShaderMaterial( { defines: { SAMPLE_RATE: 2.0 / 8.0, HALF_SAMPLE_RATE: 1.0 / 8.0 }, uniforms: { shadow_pass: { value: null }, resolution: { value: new Vector2() }, radius: { value: 4.0 } }, vertexShader: vsm_vert, fragmentShader: vsm_frag } ); var shadowMaterialHorizonal = shadowMaterialVertical.clone(); shadowMaterialHorizonal.defines.HORIZONAL_PASS = 1; var fullScreenTri = new BufferGeometry(); fullScreenTri.setAttribute( "position", new BufferAttribute( new Float32Array( [ - 1, - 1, 0.5, 3, - 1, 0.5, - 1, 3, 0.5 ] ), 3 ) ); var fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical ); var scope = this; this.enabled = false; this.autoUpdate = true; this.needsUpdate = false; this.type = PCFShadowMap; this.render = function ( lights, scene, camera ) { if ( scope.enabled === false ) { return; } if ( scope.autoUpdate === false && scope.needsUpdate === false ) { return; } if ( lights.length === 0 ) { return; } var currentRenderTarget = _renderer.getRenderTarget(); var activeCubeFace = _renderer.getActiveCubeFace(); var activeMipmapLevel = _renderer.getActiveMipmapLevel(); var _state = _renderer.state; // Set GL state for depth map. _state.setBlending( NoBlending ); _state.buffers.color.setClear( 1, 1, 1, 1 ); _state.buffers.depth.setTest( true ); _state.setScissorTest( false ); // render depth map for ( var i = 0, il = lights.length; i < il; i ++ ) { var light = lights[ i ]; var shadow = light.shadow; if ( shadow === undefined ) { console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' ); continue; } _shadowMapSize.copy( shadow.mapSize ); var shadowFrameExtents = shadow.getFrameExtents(); _shadowMapSize.multiply( shadowFrameExtents ); _viewportSize.copy( shadow.mapSize ); if ( _shadowMapSize.x > maxTextureSize || _shadowMapSize.y > maxTextureSize ) { console.warn( 'THREE.WebGLShadowMap:', light, 'has shadow exceeding max texture size, reducing' ); if ( _shadowMapSize.x > maxTextureSize ) { _viewportSize.x = Math.floor( maxTextureSize / shadowFrameExtents.x ); _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x; shadow.mapSize.x = _viewportSize.x; } if ( _shadowMapSize.y > maxTextureSize ) { _viewportSize.y = Math.floor( maxTextureSize / shadowFrameExtents.y ); _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y; shadow.mapSize.y = _viewportSize.y; } } if ( shadow.map === null && ! shadow.isPointLightShadow && this.type === VSMShadowMap ) { var pars = { minFilter: LinearFilter, magFilter: LinearFilter, format: RGBAFormat }; shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars ); shadow.map.texture.name = light.name + ".shadowMap"; shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars ); shadow.camera.updateProjectionMatrix(); } if ( shadow.map === null ) { var pars = { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat }; shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars ); shadow.map.texture.name = light.name + ".shadowMap"; shadow.camera.updateProjectionMatrix(); } _renderer.setRenderTarget( shadow.map ); _renderer.clear(); var viewportCount = shadow.getViewportCount(); for ( var vp = 0; vp < viewportCount; vp ++ ) { var viewport = shadow.getViewport( vp ); _viewport.set( _viewportSize.x * viewport.x, _viewportSize.y * viewport.y, _viewportSize.x * viewport.z, _viewportSize.y * viewport.w ); _state.viewport( _viewport ); shadow.updateMatrices( light, vp ); _frustum = shadow.getFrustum(); renderObject( scene, camera, shadow.camera, light, this.type ); } // do blur pass for VSM if ( ! shadow.isPointLightShadow && this.type === VSMShadowMap ) { VSMPass( shadow, camera ); } } scope.needsUpdate = false; _renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel ); }; function VSMPass( shadow, camera ) { var geometry = _objects.update( fullScreenMesh ); // vertical pass shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture; shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize; shadowMaterialVertical.uniforms.radius.value = shadow.radius; _renderer.setRenderTarget( shadow.mapPass ); _renderer.clear(); _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null ); // horizonal pass shadowMaterialHorizonal.uniforms.shadow_pass.value = shadow.mapPass.texture; shadowMaterialHorizonal.uniforms.resolution.value = shadow.mapSize; shadowMaterialHorizonal.uniforms.radius.value = shadow.radius; _renderer.setRenderTarget( shadow.map ); _renderer.clear(); _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizonal, fullScreenMesh, null ); } function getDepthMaterialVariant( useMorphing, useSkinning, useInstancing ) { var index = useMorphing << 0 | useSkinning << 1 | useInstancing << 2; var material = _depthMaterials[ index ]; if ( material === undefined ) { material = new MeshDepthMaterial( { depthPacking: RGBADepthPacking, morphTargets: useMorphing, skinning: useSkinning } ); _depthMaterials[ index ] = material; } return material; } function getDistanceMaterialVariant( useMorphing, useSkinning, useInstancing ) { var index = useMorphing << 0 | useSkinning << 1 | useInstancing << 2; var material = _distanceMaterials[ index ]; if ( material === undefined ) { material = new MeshDistanceMaterial( { morphTargets: useMorphing, skinning: useSkinning } ); _distanceMaterials[ index ] = material; } return material; } function getDepthMaterial( object, material, light, shadowCameraNear, shadowCameraFar, type ) { var geometry = object.geometry; var result = null; var getMaterialVariant = getDepthMaterialVariant; var customMaterial = object.customDepthMaterial; if ( light.isPointLight === true ) { getMaterialVariant = getDistanceMaterialVariant; customMaterial = object.customDistanceMaterial; } if ( customMaterial === undefined ) { var useMorphing = false; if ( material.morphTargets === true ) { if ( geometry.isBufferGeometry === true ) { useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0; } else if ( geometry.isGeometry === true ) { useMorphing = geometry.morphTargets && geometry.morphTargets.length > 0; } } var useSkinning = false; if ( object.isSkinnedMesh === true ) { if ( material.skinning === true ) { useSkinning = true; } else { console.warn( 'THREE.WebGLShadowMap: THREE.SkinnedMesh with material.skinning set to false:', object ); } } var useInstancing = object.isInstancedMesh === true; result = getMaterialVariant( useMorphing, useSkinning, useInstancing ); } else { result = customMaterial; } if ( _renderer.localClippingEnabled && material.clipShadows === true && material.clippingPlanes.length !== 0 ) { // in this case we need a unique material instance reflecting the // appropriate state var keyA = result.uuid, keyB = material.uuid; var materialsForVariant = _materialCache[ keyA ]; if ( materialsForVariant === undefined ) { materialsForVariant = {}; _materialCache[ keyA ] = materialsForVariant; } var cachedMaterial = materialsForVariant[ keyB ]; if ( cachedMaterial === undefined ) { cachedMaterial = result.clone(); materialsForVariant[ keyB ] = cachedMaterial; } result = cachedMaterial; } result.visible = material.visible; result.wireframe = material.wireframe; if ( type === VSMShadowMap ) { result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side; } else { result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ]; } result.clipShadows = material.clipShadows; result.clippingPlanes = material.clippingPlanes; result.clipIntersection = material.clipIntersection; result.wireframeLinewidth = material.wireframeLinewidth; result.linewidth = material.linewidth; if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) { result.referencePosition.setFromMatrixPosition( light.matrixWorld ); result.nearDistance = shadowCameraNear; result.farDistance = shadowCameraFar; } return result; } function renderObject( object, camera, shadowCamera, light, type ) { if ( object.visible === false ) { return; } var visible = object.layers.test( camera.layers ); if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) { if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) { object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld ); var geometry = _objects.update( object ); var material = object.material; if ( Array.isArray( material ) ) { var groups = geometry.groups; for ( var k = 0, kl = groups.length; k < kl; k ++ ) { var group = groups[ k ]; var groupMaterial = material[ group.materialIndex ]; if ( groupMaterial && groupMaterial.visible ) { var depthMaterial = getDepthMaterial( object, groupMaterial, light, shadowCamera.near, shadowCamera.far, type ); _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group ); } } } else if ( material.visible ) { var depthMaterial = getDepthMaterial( object, material, light, shadowCamera.near, shadowCamera.far, type ); _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null ); } } } var children = object.children; for ( var i = 0, l = children.length; i < l; i ++ ) { renderObject( children[ i ], camera, shadowCamera, light, type ); } } } /** * @author mrdoob / http://mrdoob.com/ */ function WebGLState( gl, extensions, capabilities ) { var isWebGL2 = capabilities.isWebGL2; function ColorBuffer() { var locked = false; var color = new Vector4(); var currentColorMask = null; var currentColorClear = new Vector4( 0, 0, 0, 0 ); return { setMask: function ( colorMask ) { if ( currentColorMask !== colorMask && ! locked ) { gl.colorMask( colorMask, colorMask, colorMask, colorMask ); currentColorMask = colorMask; } }, setLocked: function ( lock ) { locked = lock; }, setClear: function ( r, g, b, a, premultipliedAlpha ) { if ( premultipliedAlpha === true ) { r *= a; g *= a; b *= a; } color.set( r, g, b, a ); if ( currentColorClear.equals( color ) === false ) { gl.clearColor( r, g, b, a ); currentColorClear.copy( color ); } }, reset: function () { locked = false; currentColorMask = null; currentColorClear.set( - 1, 0, 0, 0 ); // set to invalid state } }; } function DepthBuffer() { var locked = false; var currentDepthMask = null; var currentDepthFunc = null; var currentDepthClear = null; return { setTest: function ( depthTest ) { if ( depthTest ) { enable( 2929 ); } else { disable( 2929 ); } }, setMask: function ( depthMask ) { if ( currentDepthMask !== depthMask && ! locked ) { gl.depthMask( depthMask ); currentDepthMask = depthMask; } }, setFunc: function ( depthFunc ) { if ( currentDepthFunc !== depthFunc ) { if ( depthFunc ) { switch ( depthFunc ) { case NeverDepth: gl.depthFunc( 512 ); break; case AlwaysDepth: gl.depthFunc( 519 ); break; case LessDepth: gl.depthFunc( 513 ); break; case LessEqualDepth: gl.depthFunc( 515 ); break; case EqualDepth: gl.depthFunc( 514 ); break; case GreaterEqualDepth: gl.depthFunc( 518 ); break; case GreaterDepth: gl.depthFunc( 516 ); break; case NotEqualDepth: gl.depthFunc( 517 ); break; default: gl.depthFunc( 515 ); } } else { gl.depthFunc( 515 ); } currentDepthFunc = depthFunc; } }, setLocked: function ( lock ) { locked = lock; }, setClear: function ( depth ) { if ( currentDepthClear !== depth ) { gl.clearDepth( depth ); currentDepthClear = depth; } }, reset: function () { locked = false; currentDepthMask = null; currentDepthFunc = null; currentDepthClear = null; } }; } function StencilBuffer() { var locked = false; var currentStencilMask = null; var currentStencilFunc = null; var currentStencilRef = null; var currentStencilFuncMask = null; var currentStencilFail = null; var currentStencilZFail = null; var currentStencilZPass = null; var currentStencilClear = null; return { setTest: function ( stencilTest ) { if ( ! locked ) { if ( stencilTest ) { enable( 2960 ); } else { disable( 2960 ); } } }, setMask: function ( stencilMask ) { if ( currentStencilMask !== stencilMask && ! locked ) { gl.stencilMask( stencilMask ); currentStencilMask = stencilMask; } }, setFunc: function ( stencilFunc, stencilRef, stencilMask ) { if ( currentStencilFunc !== stencilFunc || currentStencilRef !== stencilRef || currentStencilFuncMask !== stencilMask ) { gl.stencilFunc( stencilFunc, stencilRef, stencilMask ); currentStencilFunc = stencilFunc; currentStencilRef = stencilRef; currentStencilFuncMask = stencilMask; } }, setOp: function ( stencilFail, stencilZFail, stencilZPass ) { if ( currentStencilFail !== stencilFail || currentStencilZFail !== stencilZFail || currentStencilZPass !== stencilZPass ) { gl.stencilOp( stencilFail, stencilZFail, stencilZPass ); currentStencilFail = stencilFail; currentStencilZFail = stencilZFail; currentStencilZPass = stencilZPass; } }, setLocked: function ( lock ) { locked = lock; }, setClear: function ( stencil ) { if ( currentStencilClear !== stencil ) { gl.clearStencil( stencil ); currentStencilClear = stencil; } }, reset: function () { locked = false; currentStencilMask = null; currentStencilFunc = null; currentStencilRef = null; currentStencilFuncMask = null; currentStencilFail = null; currentStencilZFail = null; currentStencilZPass = null; currentStencilClear = null; } }; } // var colorBuffer = new ColorBuffer(); var depthBuffer = new DepthBuffer(); var stencilBuffer = new StencilBuffer(); var maxVertexAttributes = gl.getParameter( 34921 ); var newAttributes = new Uint8Array( maxVertexAttributes ); var enabledAttributes = new Uint8Array( maxVertexAttributes ); var attributeDivisors = new Uint8Array( maxVertexAttributes ); var enabledCapabilities = {}; var currentProgram = null; var currentBlendingEnabled = null; var currentBlending = null; var currentBlendEquation = null; var currentBlendSrc = null; var currentBlendDst = null; var currentBlendEquationAlpha = null; var currentBlendSrcAlpha = null; var currentBlendDstAlpha = null; var currentPremultipledAlpha = false; var currentFlipSided = null; var currentCullFace = null; var currentLineWidth = null; var currentPolygonOffsetFactor = null; var currentPolygonOffsetUnits = null; var maxTextures = gl.getParameter( 35661 ); var lineWidthAvailable = false; var version = 0; var glVersion = gl.getParameter( 7938 ); if ( glVersion.indexOf( 'WebGL' ) !== - 1 ) { version = parseFloat( /^WebGL\ ([0-9])/.exec( glVersion )[ 1 ] ); lineWidthAvailable = ( version >= 1.0 ); } else if ( glVersion.indexOf( 'OpenGL ES' ) !== - 1 ) { version = parseFloat( /^OpenGL\ ES\ ([0-9])/.exec( glVersion )[ 1 ] ); lineWidthAvailable = ( version >= 2.0 ); } var currentTextureSlot = null; var currentBoundTextures = {}; var currentScissor = new Vector4(); var currentViewport = new Vector4(); function createTexture( type, target, count ) { var data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4. var texture = gl.createTexture(); gl.bindTexture( type, texture ); gl.texParameteri( type, 10241, 9728 ); gl.texParameteri( type, 10240, 9728 ); for ( var i = 0; i < count; i ++ ) { gl.texImage2D( target + i, 0, 6408, 1, 1, 0, 6408, 5121, data ); } return texture; } var emptyTextures = {}; emptyTextures[ 3553 ] = createTexture( 3553, 3553, 1 ); emptyTextures[ 34067 ] = createTexture( 34067, 34069, 6 ); // init colorBuffer.setClear( 0, 0, 0, 1 ); depthBuffer.setClear( 1 ); stencilBuffer.setClear( 0 ); enable( 2929 ); depthBuffer.setFunc( LessEqualDepth ); setFlipSided( false ); setCullFace( CullFaceBack ); enable( 2884 ); setBlending( NoBlending ); // function initAttributes() { for ( var i = 0, l = newAttributes.length; i < l; i ++ ) { newAttributes[ i ] = 0; } } function enableAttribute( attribute ) { enableAttributeAndDivisor( attribute, 0 ); } function enableAttributeAndDivisor( attribute, meshPerAttribute ) { newAttributes[ attribute ] = 1; if ( enabledAttributes[ attribute ] === 0 ) { gl.enableVertexAttribArray( attribute ); enabledAttributes[ attribute ] = 1; } if ( attributeDivisors[ attribute ] !== meshPerAttribute ) { var extension = isWebGL2 ? gl : extensions.get( 'ANGLE_instanced_arrays' ); extension[ isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE' ]( attribute, meshPerAttribute ); attributeDivisors[ attribute ] = meshPerAttribute; } } function disableUnusedAttributes() { for ( var i = 0, l = enabledAttributes.length; i !== l; ++ i ) { if ( enabledAttributes[ i ] !== newAttributes[ i ] ) { gl.disableVertexAttribArray( i ); enabledAttributes[ i ] = 0; } } } function enable( id ) { if ( enabledCapabilities[ id ] !== true ) { gl.enable( id ); enabledCapabilities[ id ] = true; } } function disable( id ) { if ( enabledCapabilities[ id ] !== false ) { gl.disable( id ); enabledCapabilities[ id ] = false; } } function useProgram( program ) { if ( currentProgram !== program ) { gl.useProgram( program ); currentProgram = program; return true; } return false; } var equationToGL = {}; equationToGL[ AddEquation ] = 32774; equationToGL[ SubtractEquation ] = 32778; equationToGL[ ReverseSubtractEquation ] = 32779; if ( isWebGL2 ) { equationToGL[ MinEquation ] = 32775; equationToGL[ MaxEquation ] = 32776; } else { var extension = extensions.get( 'EXT_blend_minmax' ); if ( extension !== null ) { equationToGL[ MinEquation ] = extension.MIN_EXT; equationToGL[ MaxEquation ] = extension.MAX_EXT; } } var factorToGL = {}; factorToGL[ ZeroFactor ] = 0; factorToGL[ OneFactor ] = 1; factorToGL[ SrcColorFactor ] = 768; factorToGL[ SrcAlphaFactor ] = 770; factorToGL[ SrcAlphaSaturateFactor ] = 776; factorToGL[ DstColorFactor ] = 774; factorToGL[ DstAlphaFactor ] = 772; factorToGL[ OneMinusSrcColorFactor ] = 769; factorToGL[ OneMinusSrcAlphaFactor ] = 771; factorToGL[ OneMinusDstColorFactor ] = 775; factorToGL[ OneMinusDstAlphaFactor ] = 773; function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) { if ( blending === NoBlending ) { if ( currentBlendingEnabled ) { disable( 3042 ); currentBlendingEnabled = false; } return; } if ( ! currentBlendingEnabled ) { enable( 3042 ); currentBlendingEnabled = true; } if ( blending !== CustomBlending ) { if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) { if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) { gl.blendEquation( 32774 ); currentBlendEquation = AddEquation; currentBlendEquationAlpha = AddEquation; } if ( premultipliedAlpha ) { switch ( blending ) { case NormalBlending: gl.blendFuncSeparate( 1, 771, 1, 771 ); break; case AdditiveBlending: gl.blendFunc( 1, 1 ); break; case SubtractiveBlending: gl.blendFuncSeparate( 0, 0, 769, 771 ); break; case MultiplyBlending: gl.blendFuncSeparate( 0, 768, 0, 770 ); break; default: console.error( 'THREE.WebGLState: Invalid blending: ', blending ); break; } } else { switch ( blending ) { case NormalBlending: gl.blendFuncSeparate( 770, 771, 1, 771 ); break; case AdditiveBlending: gl.blendFunc( 770, 1 ); break; case SubtractiveBlending: gl.blendFunc( 0, 769 ); break; case MultiplyBlending: gl.blendFunc( 0, 768 ); break; default: console.error( 'THREE.WebGLState: Invalid blending: ', blending ); break; } } currentBlendSrc = null; currentBlendDst = null; currentBlendSrcAlpha = null; currentBlendDstAlpha = null; currentBlending = blending; currentPremultipledAlpha = premultipliedAlpha; } return; } // custom blending blendEquationAlpha = blendEquationAlpha || blendEquation; blendSrcAlpha = blendSrcAlpha || blendSrc; blendDstAlpha = blendDstAlpha || blendDst; if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) { gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] ); currentBlendEquation = blendEquation; currentBlendEquationAlpha = blendEquationAlpha; } if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) { gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] ); currentBlendSrc = blendSrc; currentBlendDst = blendDst; currentBlendSrcAlpha = blendSrcAlpha; currentBlendDstAlpha = blendDstAlpha; } currentBlending = blending; currentPremultipledAlpha = null; } function setMaterial( material, frontFaceCW ) { material.side === DoubleSide ? disable( 2884 ) : enable( 2884 ); var flipSided = ( material.side === BackSide ); if ( frontFaceCW ) { flipSided = ! flipSided; } setFlipSided( flipSided ); ( material.blending === NormalBlending && material.transparent === false ) ? setBlending( NoBlending ) : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha ); depthBuffer.setFunc( material.depthFunc ); depthBuffer.setTest( material.depthTest ); depthBuffer.setMask( material.depthWrite ); colorBuffer.setMask( material.colorWrite ); var stencilWrite = material.stencilWrite; stencilBuffer.setTest( stencilWrite ); if ( stencilWrite ) { stencilBuffer.setMask( material.stencilWriteMask ); stencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask ); stencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass ); } setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits ); } // function setFlipSided( flipSided ) { if ( currentFlipSided !== flipSided ) { if ( flipSided ) { gl.frontFace( 2304 ); } else { gl.frontFace( 2305 ); } currentFlipSided = flipSided; } } function setCullFace( cullFace ) { if ( cullFace !== CullFaceNone ) { enable( 2884 ); if ( cullFace !== currentCullFace ) { if ( cullFace === CullFaceBack ) { gl.cullFace( 1029 ); } else if ( cullFace === CullFaceFront ) { gl.cullFace( 1028 ); } else { gl.cullFace( 1032 ); } } } else { disable( 2884 ); } currentCullFace = cullFace; } function setLineWidth( width ) { if ( width !== currentLineWidth ) { if ( lineWidthAvailable ) { gl.lineWidth( width ); } currentLineWidth = width; } } function setPolygonOffset( polygonOffset, factor, units ) { if ( polygonOffset ) { enable( 32823 ); if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) { gl.polygonOffset( factor, units ); currentPolygonOffsetFactor = factor; currentPolygonOffsetUnits = units; } } else { disable( 32823 ); } } function setScissorTest( scissorTest ) { if ( scissorTest ) { enable( 3089 ); } else { disable( 3089 ); } } // texture function activeTexture( webglSlot ) { if ( webglSlot === undefined ) { webglSlot = 33984 + maxTextures - 1; } if ( currentTextureSlot !== webglSlot ) { gl.activeTexture( webglSlot ); currentTextureSlot = webglSlot; } } function bindTexture( webglType, webglTexture ) { if ( currentTextureSlot === null ) { activeTexture(); } var boundTexture = currentBoundTextures[ currentTextureSlot ]; if ( boundTexture === undefined ) { boundTexture = { type: undefined, texture: undefined }; currentBoundTextures[ currentTextureSlot ] = boundTexture; } if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) { gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] ); boundTexture.type = webglType; boundTexture.texture = webglTexture; } } function unbindTexture() { var boundTexture = currentBoundTextures[ currentTextureSlot ]; if ( boundTexture !== undefined && boundTexture.type !== undefined ) { gl.bindTexture( boundTexture.type, null ); boundTexture.type = undefined; boundTexture.texture = undefined; } } function compressedTexImage2D() { try { gl.compressedTexImage2D.apply( gl, arguments ); } catch ( error ) { console.error( 'THREE.WebGLState:', error ); } } function texImage2D() { try { gl.texImage2D.apply( gl, arguments ); } catch ( error ) { console.error( 'THREE.WebGLState:', error ); } } function texImage3D() { try { gl.texImage3D.apply( gl, arguments ); } catch ( error ) { console.error( 'THREE.WebGLState:', error ); } } // function scissor( scissor ) { if ( currentScissor.equals( scissor ) === false ) { gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w ); currentScissor.copy( scissor ); } } function viewport( viewport ) { if ( currentViewport.equals( viewport ) === false ) { gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w ); currentViewport.copy( viewport ); } } // function reset() { for ( var i = 0; i < enabledAttributes.length; i ++ ) { if ( enabledAttributes[ i ] === 1 ) { gl.disableVertexAttribArray( i ); enabledAttributes[ i ] = 0; } } enabledCapabilities = {}; currentTextureSlot = null; currentBoundTextures = {}; currentProgram = null; currentBlending = null; currentFlipSided = null; currentCullFace = null; colorBuffer.reset(); depthBuffer.reset(); stencilBuffer.reset(); } return { buffers: { color: colorBuffer, depth: depthBuffer, stencil: stencilBuffer }, initAttributes: initAttributes, enableAttribute: enableAttribute, enableAttributeAndDivisor: enableAttributeAndDivisor, disableUnusedAttributes: disableUnusedAttributes, enable: enable, disable: disable, useProgram: useProgram, setBlending: setBlending, setMaterial: setMaterial, setFlipSided: setFlipSided, setCullFace: setCullFace, setLineWidth: setLineWidth, setPolygonOffset: setPolygonOffset, setScissorTest: setScissorTest, activeTexture: activeTexture, bindTexture: bindTexture, unbindTexture: unbindTexture, compressedTexImage2D: compressedTexImage2D, texImage2D: texImage2D, texImage3D: texImage3D, scissor: scissor, viewport: viewport, reset: reset }; } /** * @author mrdoob / http://mrdoob.com/ */ function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) { var isWebGL2 = capabilities.isWebGL2; var maxTextures = capabilities.maxTextures; var maxCubemapSize = capabilities.maxCubemapSize; var maxTextureSize = capabilities.maxTextureSize; var maxSamples = capabilities.maxSamples; var _videoTextures = new WeakMap(); var _canvas; // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas, // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")! // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d). var useOffscreenCanvas = false; try { useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined' && ( new OffscreenCanvas( 1, 1 ).getContext( "2d" ) ) !== null; } catch ( err ) { // Ignore any errors } function createCanvas( width, height ) { // Use OffscreenCanvas when available. Specially needed in web workers return useOffscreenCanvas ? new OffscreenCanvas( width, height ) : document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ); } function resizeImage( image, needsPowerOfTwo, needsNewCanvas, maxSize ) { var scale = 1; // handle case if texture exceeds max size if ( image.width > maxSize || image.height > maxSize ) { scale = maxSize / Math.max( image.width, image.height ); } // only perform resize if necessary if ( scale < 1 || needsPowerOfTwo === true ) { // only perform resize for certain image types if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) || ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) || ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) { var floor = needsPowerOfTwo ? MathUtils.floorPowerOfTwo : Math.floor; var width = floor( scale * image.width ); var height = floor( scale * image.height ); if ( _canvas === undefined ) { _canvas = createCanvas( width, height ); } // cube textures can't reuse the same canvas var canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas; canvas.width = width; canvas.height = height; var context = canvas.getContext( '2d' ); context.drawImage( image, 0, 0, width, height ); console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').' ); return canvas; } else { if ( 'data' in image ) { console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').' ); } return image; } } return image; } function isPowerOfTwo( image ) { return MathUtils.isPowerOfTwo( image.width ) && MathUtils.isPowerOfTwo( image.height ); } function textureNeedsPowerOfTwo( texture ) { if ( isWebGL2 ) { return false; } return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) || ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ); } function textureNeedsGenerateMipmaps( texture, supportsMips ) { return texture.generateMipmaps && supportsMips && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter; } function generateMipmap( target, texture, width, height ) { _gl.generateMipmap( target ); var textureProperties = properties.get( texture ); // Note: Math.log( x ) * Math.LOG2E used instead of Math.log2( x ) which is not supported by IE11 textureProperties.__maxMipLevel = Math.log( Math.max( width, height ) ) * Math.LOG2E; } function getInternalFormat( internalFormatName, glFormat, glType ) { if ( isWebGL2 === false ) { return glFormat; } if ( internalFormatName !== null ) { if ( _gl[ internalFormatName ] !== undefined ) { return _gl[ internalFormatName ]; } console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' ); } var internalFormat = glFormat; if ( glFormat === 6403 ) { if ( glType === 5126 ) { internalFormat = 33326; } if ( glType === 5131 ) { internalFormat = 33325; } if ( glType === 5121 ) { internalFormat = 33321; } } if ( glFormat === 6407 ) { if ( glType === 5126 ) { internalFormat = 34837; } if ( glType === 5131 ) { internalFormat = 34843; } if ( glType === 5121 ) { internalFormat = 32849; } } if ( glFormat === 6408 ) { if ( glType === 5126 ) { internalFormat = 34836; } if ( glType === 5131 ) { internalFormat = 34842; } if ( glType === 5121 ) { internalFormat = 32856; } } if ( internalFormat === 33325 || internalFormat === 33326 || internalFormat === 34842 || internalFormat === 34836 ) { extensions.get( 'EXT_color_buffer_float' ); } else if ( internalFormat === 34843 || internalFormat === 34837 ) { console.warn( 'THREE.WebGLRenderer: Floating point textures with RGB format not supported. Please use RGBA instead.' ); } return internalFormat; } // Fallback filters for non-power-of-2 textures function filterFallback( f ) { if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) { return 9728; } return 9729; } // function onTextureDispose( event ) { var texture = event.target; texture.removeEventListener( 'dispose', onTextureDispose ); deallocateTexture( texture ); if ( texture.isVideoTexture ) { _videoTextures.delete( texture ); } info.memory.textures --; } function onRenderTargetDispose( event ) { var renderTarget = event.target; renderTarget.removeEventListener( 'dispose', onRenderTargetDispose ); deallocateRenderTarget( renderTarget ); info.memory.textures --; } // function deallocateTexture( texture ) { var textureProperties = properties.get( texture ); if ( textureProperties.__webglInit === undefined ) { return; } _gl.deleteTexture( textureProperties.__webglTexture ); properties.remove( texture ); } function deallocateRenderTarget( renderTarget ) { var renderTargetProperties = properties.get( renderTarget ); var textureProperties = properties.get( renderTarget.texture ); if ( ! renderTarget ) { return; } if ( textureProperties.__webglTexture !== undefined ) { _gl.deleteTexture( textureProperties.__webglTexture ); } if ( renderTarget.depthTexture ) { renderTarget.depthTexture.dispose(); } if ( renderTarget.isWebGLCubeRenderTarget ) { for ( var i = 0; i < 6; i ++ ) { _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] ); if ( renderTargetProperties.__webglDepthbuffer ) { _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] ); } } } else { _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer ); if ( renderTargetProperties.__webglDepthbuffer ) { _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer ); } } if ( renderTarget.isWebGLMultiviewRenderTarget ) { _gl.deleteTexture( renderTargetProperties.__webglColorTexture ); _gl.deleteTexture( renderTargetProperties.__webglDepthStencilTexture ); info.memory.textures -= 2; for ( var i = 0, il = renderTargetProperties.__webglViewFramebuffers.length; i < il; i ++ ) { _gl.deleteFramebuffer( renderTargetProperties.__webglViewFramebuffers[ i ] ); } } properties.remove( renderTarget.texture ); properties.remove( renderTarget ); } // var textureUnits = 0; function resetTextureUnits() { textureUnits = 0; } function allocateTextureUnit() { var textureUnit = textureUnits; if ( textureUnit >= maxTextures ) { console.warn( 'THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures ); } textureUnits += 1; return textureUnit; } // function setTexture2D( texture, slot ) { var textureProperties = properties.get( texture ); if ( texture.isVideoTexture ) { updateVideoTexture( texture ); } if ( texture.version > 0 && textureProperties.__version !== texture.version ) { var image = texture.image; if ( image === undefined ) { console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined' ); } else if ( image.complete === false ) { console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' ); } else { uploadTexture( textureProperties, texture, slot ); return; } } state.activeTexture( 33984 + slot ); state.bindTexture( 3553, textureProperties.__webglTexture ); } function setTexture2DArray( texture, slot ) { var textureProperties = properties.get( texture ); if ( texture.version > 0 && textureProperties.__version !== texture.version ) { uploadTexture( textureProperties, texture, slot ); return; } state.activeTexture( 33984 + slot ); state.bindTexture( 35866, textureProperties.__webglTexture ); } function setTexture3D( texture, slot ) { var textureProperties = properties.get( texture ); if ( texture.version > 0 && textureProperties.__version !== texture.version ) { uploadTexture( textureProperties, texture, slot ); return; } state.activeTexture( 33984 + slot ); state.bindTexture( 32879, textureProperties.__webglTexture ); } function setTextureCube( texture, slot ) { if ( texture.image.length !== 6 ) { return; } var textureProperties = properties.get( texture ); if ( texture.version > 0 && textureProperties.__version !== texture.version ) { initTexture( textureProperties, texture ); state.activeTexture( 33984 + slot ); state.bindTexture( 34067, textureProperties.__webglTexture ); _gl.pixelStorei( 37440, texture.flipY ); var isCompressed = ( texture && ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture ) ); var isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture ); var cubeImage = []; for ( var i = 0; i < 6; i ++ ) { if ( ! isCompressed && ! isDataTexture ) { cubeImage[ i ] = resizeImage( texture.image[ i ], false, true, maxCubemapSize ); } else { cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ]; } } var image = cubeImage[ 0 ], supportsMips = isPowerOfTwo( image ) || isWebGL2, glFormat = utils.convert( texture.format ), glType = utils.convert( texture.type ), glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType ); setTextureParameters( 34067, texture, supportsMips ); var mipmaps; if ( isCompressed ) { for ( var i = 0; i < 6; i ++ ) { mipmaps = cubeImage[ i ].mipmaps; for ( var j = 0; j < mipmaps.length; j ++ ) { var mipmap = mipmaps[ j ]; if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) { if ( glFormat !== null ) { state.compressedTexImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data ); } else { console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' ); } } else { state.texImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); } } } textureProperties.__maxMipLevel = mipmaps.length - 1; } else { mipmaps = texture.mipmaps; for ( var i = 0; i < 6; i ++ ) { if ( isDataTexture ) { state.texImage2D( 34069 + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data ); for ( var j = 0; j < mipmaps.length; j ++ ) { var mipmap = mipmaps[ j ]; var mipmapImage = mipmap.image[ i ].image; state.texImage2D( 34069 + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data ); } } else { state.texImage2D( 34069 + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] ); for ( var j = 0; j < mipmaps.length; j ++ ) { var mipmap = mipmaps[ j ]; state.texImage2D( 34069 + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] ); } } } textureProperties.__maxMipLevel = mipmaps.length; } if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) { // We assume images for cube map have the same size. generateMipmap( 34067, texture, image.width, image.height ); } textureProperties.__version = texture.version; if ( texture.onUpdate ) { texture.onUpdate( texture ); } } else { state.activeTexture( 33984 + slot ); state.bindTexture( 34067, textureProperties.__webglTexture ); } } function setTextureCubeDynamic( texture, slot ) { state.activeTexture( 33984 + slot ); state.bindTexture( 34067, properties.get( texture ).__webglTexture ); } var wrappingToGL = {}; wrappingToGL[ RepeatWrapping ] = 10497; wrappingToGL[ ClampToEdgeWrapping ] = 33071; wrappingToGL[ MirroredRepeatWrapping ] = 33648; var filterToGL = {}; filterToGL[ NearestFilter ] = 9728; filterToGL[ NearestMipmapNearestFilter ] = 9984; filterToGL[ NearestMipmapLinearFilter ] = 9986; filterToGL[ LinearFilter ] = 9729; filterToGL[ LinearMipmapNearestFilter ] = 9985; filterToGL[ LinearMipmapLinearFilter ] = 9987; function setTextureParameters( textureType, texture, supportsMips ) { if ( supportsMips ) { _gl.texParameteri( textureType, 10242, wrappingToGL[ texture.wrapS ] ); _gl.texParameteri( textureType, 10243, wrappingToGL[ texture.wrapT ] ); if ( textureType === 32879 || textureType === 35866 ) { _gl.texParameteri( textureType, 32882, wrappingToGL[ texture.wrapR ] ); } _gl.texParameteri( textureType, 10240, filterToGL[ texture.magFilter ] ); _gl.texParameteri( textureType, 10241, filterToGL[ texture.minFilter ] ); } else { _gl.texParameteri( textureType, 10242, 33071 ); _gl.texParameteri( textureType, 10243, 33071 ); if ( textureType === 32879 || textureType === 35866 ) { _gl.texParameteri( textureType, 32882, 33071 ); } if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) { console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.' ); } _gl.texParameteri( textureType, 10240, filterFallback( texture.magFilter ) ); _gl.texParameteri( textureType, 10241, filterFallback( texture.minFilter ) ); if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) { console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.' ); } } var extension = extensions.get( 'EXT_texture_filter_anisotropic' ); if ( extension ) { if ( texture.type === FloatType && extensions.get( 'OES_texture_float_linear' ) === null ) { return; } if ( texture.type === HalfFloatType && ( isWebGL2 || extensions.get( 'OES_texture_half_float_linear' ) ) === null ) { return; } if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) { _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) ); properties.get( texture ).__currentAnisotropy = texture.anisotropy; } } } function initTexture( textureProperties, texture ) { if ( textureProperties.__webglInit === undefined ) { textureProperties.__webglInit = true; texture.addEventListener( 'dispose', onTextureDispose ); textureProperties.__webglTexture = _gl.createTexture(); info.memory.textures ++; } } function uploadTexture( textureProperties, texture, slot ) { var textureType = 3553; if ( texture.isDataTexture2DArray ) { textureType = 35866; } if ( texture.isDataTexture3D ) { textureType = 32879; } initTexture( textureProperties, texture ); state.activeTexture( 33984 + slot ); state.bindTexture( textureType, textureProperties.__webglTexture ); _gl.pixelStorei( 37440, texture.flipY ); _gl.pixelStorei( 37441, texture.premultiplyAlpha ); _gl.pixelStorei( 3317, texture.unpackAlignment ); var needsPowerOfTwo = textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( texture.image ) === false; var image = resizeImage( texture.image, needsPowerOfTwo, false, maxTextureSize ); var supportsMips = isPowerOfTwo( image ) || isWebGL2, glFormat = utils.convert( texture.format ), glType = utils.convert( texture.type ), glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType ); setTextureParameters( textureType, texture, supportsMips ); var mipmap, mipmaps = texture.mipmaps; if ( texture.isDepthTexture ) { // populate depth texture with dummy data glInternalFormat = 6402; if ( texture.type === FloatType ) { if ( isWebGL2 === false ) { throw new Error( 'Float Depth Texture only supported in WebGL2.0' ); } glInternalFormat = 36012; } else if ( isWebGL2 ) { // WebGL 2.0 requires signed internalformat for glTexImage2D glInternalFormat = 33189; } if ( texture.format === DepthFormat && glInternalFormat === 6402 ) { // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/) if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) { console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' ); texture.type = UnsignedShortType; glType = utils.convert( texture.type ); } } // Depth stencil textures need the DEPTH_STENCIL internal format // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/) if ( texture.format === DepthStencilFormat ) { glInternalFormat = 34041; // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/) if ( texture.type !== UnsignedInt248Type ) { console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' ); texture.type = UnsignedInt248Type; glType = utils.convert( texture.type ); } } state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null ); } else if ( texture.isDataTexture ) { // use manually created mipmaps if available // if there are no manual mipmaps // set 0 level mipmap and then use GL to generate other mipmap levels if ( mipmaps.length > 0 && supportsMips ) { for ( var i = 0, il = mipmaps.length; i < il; i ++ ) { mipmap = mipmaps[ i ]; state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); } texture.generateMipmaps = false; textureProperties.__maxMipLevel = mipmaps.length - 1; } else { state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data ); textureProperties.__maxMipLevel = 0; } } else if ( texture.isCompressedTexture ) { for ( var i = 0, il = mipmaps.length; i < il; i ++ ) { mipmap = mipmaps[ i ]; if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) { if ( glFormat !== null ) { state.compressedTexImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data ); } else { console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' ); } } else { state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data ); } } textureProperties.__maxMipLevel = mipmaps.length - 1; } else if ( texture.isDataTexture2DArray ) { state.texImage3D( 35866, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data ); textureProperties.__maxMipLevel = 0; } else if ( texture.isDataTexture3D ) { state.texImage3D( 32879, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data ); textureProperties.__maxMipLevel = 0; } else { // regular Texture (image, video, canvas) // use manually created mipmaps if available // if there are no manual mipmaps // set 0 level mipmap and then use GL to generate other mipmap levels if ( mipmaps.length > 0 && supportsMips ) { for ( var i = 0, il = mipmaps.length; i < il; i ++ ) { mipmap = mipmaps[ i ]; state.texImage2D( 3553, i, glInternalFormat, glFormat, glType, mipmap ); } texture.generateMipmaps = false; textureProperties.__maxMipLevel = mipmaps.length - 1; } else { state.texImage2D( 3553, 0, glInternalFormat, glFormat, glType, image ); textureProperties.__maxMipLevel = 0; } } if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) { generateMipmap( textureType, texture, image.width, image.height ); } textureProperties.__version = texture.version; if ( texture.onUpdate ) { texture.onUpdate( texture ); } } // Render targets // Setup storage for target texture and bind it to correct framebuffer function setupFrameBufferTexture( framebuffer, renderTarget, attachment, textureTarget ) { var glFormat = utils.convert( renderTarget.texture.format ); var glType = utils.convert( renderTarget.texture.type ); var glInternalFormat = getInternalFormat( renderTarget.texture.internalFormat, glFormat, glType ); state.texImage2D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null ); _gl.bindFramebuffer( 36160, framebuffer ); _gl.framebufferTexture2D( 36160, attachment, textureTarget, properties.get( renderTarget.texture ).__webglTexture, 0 ); _gl.bindFramebuffer( 36160, null ); } // Setup storage for internal depth/stencil buffers and bind to correct framebuffer function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) { _gl.bindRenderbuffer( 36161, renderbuffer ); if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) { if ( isMultisample ) { var samples = getRenderTargetSamples( renderTarget ); _gl.renderbufferStorageMultisample( 36161, samples, 33189, renderTarget.width, renderTarget.height ); } else { _gl.renderbufferStorage( 36161, 33189, renderTarget.width, renderTarget.height ); } _gl.framebufferRenderbuffer( 36160, 36096, 36161, renderbuffer ); } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) { if ( isMultisample ) { var samples = getRenderTargetSamples( renderTarget ); _gl.renderbufferStorageMultisample( 36161, samples, 35056, renderTarget.width, renderTarget.height ); } else { _gl.renderbufferStorage( 36161, 34041, renderTarget.width, renderTarget.height ); } _gl.framebufferRenderbuffer( 36160, 33306, 36161, renderbuffer ); } else { var glFormat = utils.convert( renderTarget.texture.format ); var glType = utils.convert( renderTarget.texture.type ); var glInternalFormat = getInternalFormat( renderTarget.texture.internalFormat, glFormat, glType ); if ( isMultisample ) { var samples = getRenderTargetSamples( renderTarget ); _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height ); } else { _gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height ); } } _gl.bindRenderbuffer( 36161, null ); } // Setup resources for a Depth Texture for a FBO (needs an extension) function setupDepthTexture( framebuffer, renderTarget ) { var isCube = ( renderTarget && renderTarget.isWebGLCubeRenderTarget ); if ( isCube ) { throw new Error( 'Depth Texture with cube render targets is not supported' ); } _gl.bindFramebuffer( 36160, framebuffer ); if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) { throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' ); } // upload an empty depth texture with framebuffer size if ( ! properties.get( renderTarget.depthTexture ).__webglTexture || renderTarget.depthTexture.image.width !== renderTarget.width || renderTarget.depthTexture.image.height !== renderTarget.height ) { renderTarget.depthTexture.image.width = renderTarget.width; renderTarget.depthTexture.image.height = renderTarget.height; renderTarget.depthTexture.needsUpdate = true; } setTexture2D( renderTarget.depthTexture, 0 ); var webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture; if ( renderTarget.depthTexture.format === DepthFormat ) { _gl.framebufferTexture2D( 36160, 36096, 3553, webglDepthTexture, 0 ); } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) { _gl.framebufferTexture2D( 36160, 33306, 3553, webglDepthTexture, 0 ); } else { throw new Error( 'Unknown depthTexture format' ); } } // Setup GL resources for a non-texture depth buffer function setupDepthRenderbuffer( renderTarget ) { var renderTargetProperties = properties.get( renderTarget ); var isCube = ( renderTarget.isWebGLCubeRenderTarget === true ); if ( renderTarget.depthTexture ) { if ( isCube ) { throw new Error( 'target.depthTexture not supported in Cube render targets' ); } setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget ); } else { if ( isCube ) { renderTargetProperties.__webglDepthbuffer = []; for ( var i = 0; i < 6; i ++ ) { _gl.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer[ i ] ); renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer(); setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget ); } } else { _gl.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer ); renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer(); setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget ); } } _gl.bindFramebuffer( 36160, null ); } // Set up GL resources for the render target function setupRenderTarget( renderTarget ) { var renderTargetProperties = properties.get( renderTarget ); var textureProperties = properties.get( renderTarget.texture ); renderTarget.addEventListener( 'dispose', onRenderTargetDispose ); textureProperties.__webglTexture = _gl.createTexture(); info.memory.textures ++; var isCube = ( renderTarget.isWebGLCubeRenderTarget === true ); var isMultisample = ( renderTarget.isWebGLMultisampleRenderTarget === true ); var isMultiview = ( renderTarget.isWebGLMultiviewRenderTarget === true ); var supportsMips = isPowerOfTwo( renderTarget ) || isWebGL2; // Setup framebuffer if ( isCube ) { renderTargetProperties.__webglFramebuffer = []; for ( var i = 0; i < 6; i ++ ) { renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer(); } } else { renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer(); if ( isMultisample ) { if ( isWebGL2 ) { renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer(); renderTargetProperties.__webglColorRenderbuffer = _gl.createRenderbuffer(); _gl.bindRenderbuffer( 36161, renderTargetProperties.__webglColorRenderbuffer ); var glFormat = utils.convert( renderTarget.texture.format ); var glType = utils.convert( renderTarget.texture.type ); var glInternalFormat = getInternalFormat( renderTarget.texture.internalFormat, glFormat, glType ); var samples = getRenderTargetSamples( renderTarget ); _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height ); _gl.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer ); _gl.framebufferRenderbuffer( 36160, 36064, 36161, renderTargetProperties.__webglColorRenderbuffer ); _gl.bindRenderbuffer( 36161, null ); if ( renderTarget.depthBuffer ) { renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer(); setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true ); } _gl.bindFramebuffer( 36160, null ); } else { console.warn( 'THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.' ); } } else if ( isMultiview ) { var width = renderTarget.width; var height = renderTarget.height; var numViews = renderTarget.numViews; _gl.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer ); var ext = extensions.get( 'OVR_multiview2' ); info.memory.textures += 2; var colorTexture = _gl.createTexture(); _gl.bindTexture( 35866, colorTexture ); _gl.texParameteri( 35866, 10240, 9728 ); _gl.texParameteri( 35866, 10241, 9728 ); _gl.texImage3D( 35866, 0, 32856, width, height, numViews, 0, 6408, 5121, null ); ext.framebufferTextureMultiviewOVR( 36160, 36064, colorTexture, 0, 0, numViews ); var depthStencilTexture = _gl.createTexture(); _gl.bindTexture( 35866, depthStencilTexture ); _gl.texParameteri( 35866, 10240, 9728 ); _gl.texParameteri( 35866, 10241, 9728 ); _gl.texImage3D( 35866, 0, 35056, width, height, numViews, 0, 34041, 34042, null ); ext.framebufferTextureMultiviewOVR( 36160, 33306, depthStencilTexture, 0, 0, numViews ); var viewFramebuffers = new Array( numViews ); for ( var i = 0; i < numViews; ++ i ) { viewFramebuffers[ i ] = _gl.createFramebuffer(); _gl.bindFramebuffer( 36160, viewFramebuffers[ i ] ); _gl.framebufferTextureLayer( 36160, 36064, colorTexture, 0, i ); } renderTargetProperties.__webglColorTexture = colorTexture; renderTargetProperties.__webglDepthStencilTexture = depthStencilTexture; renderTargetProperties.__webglViewFramebuffers = viewFramebuffers; _gl.bindFramebuffer( 36160, null ); _gl.bindTexture( 35866, null ); } } // Setup color buffer if ( isCube ) { state.bindTexture( 34067, textureProperties.__webglTexture ); setTextureParameters( 34067, renderTarget.texture, supportsMips ); for ( var i = 0; i < 6; i ++ ) { setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, 36064, 34069 + i ); } if ( textureNeedsGenerateMipmaps( renderTarget.texture, supportsMips ) ) { generateMipmap( 34067, renderTarget.texture, renderTarget.width, renderTarget.height ); } state.bindTexture( 34067, null ); } else if ( ! isMultiview ) { state.bindTexture( 3553, textureProperties.__webglTexture ); setTextureParameters( 3553, renderTarget.texture, supportsMips ); setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, 36064, 3553 ); if ( textureNeedsGenerateMipmaps( renderTarget.texture, supportsMips ) ) { generateMipmap( 3553, renderTarget.texture, renderTarget.width, renderTarget.height ); } state.bindTexture( 3553, null ); } // Setup depth and stencil buffers if ( renderTarget.depthBuffer ) { setupDepthRenderbuffer( renderTarget ); } } function updateRenderTargetMipmap( renderTarget ) { var texture = renderTarget.texture; var supportsMips = isPowerOfTwo( renderTarget ) || isWebGL2; if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) { var target = renderTarget.isWebGLCubeRenderTarget ? 34067 : 3553; var webglTexture = properties.get( texture ).__webglTexture; state.bindTexture( target, webglTexture ); generateMipmap( target, texture, renderTarget.width, renderTarget.height ); state.bindTexture( target, null ); } } function updateMultisampleRenderTarget( renderTarget ) { if ( renderTarget.isWebGLMultisampleRenderTarget ) { if ( isWebGL2 ) { var renderTargetProperties = properties.get( renderTarget ); _gl.bindFramebuffer( 36008, renderTargetProperties.__webglMultisampledFramebuffer ); _gl.bindFramebuffer( 36009, renderTargetProperties.__webglFramebuffer ); var width = renderTarget.width; var height = renderTarget.height; var mask = 16384; if ( renderTarget.depthBuffer ) { mask |= 256; } if ( renderTarget.stencilBuffer ) { mask |= 1024; } _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, 9728 ); } else { console.warn( 'THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.' ); } } } function getRenderTargetSamples( renderTarget ) { return ( isWebGL2 && renderTarget.isWebGLMultisampleRenderTarget ) ? Math.min( maxSamples, renderTarget.samples ) : 0; } function updateVideoTexture( texture ) { var frame = info.render.frame; // Check the last frame we updated the VideoTexture if ( _videoTextures.get( texture ) !== frame ) { _videoTextures.set( texture, frame ); texture.update(); } } // backwards compatibility var warnedTexture2D = false; var warnedTextureCube = false; function safeSetTexture2D( texture, slot ) { if ( texture && texture.isWebGLRenderTarget ) { if ( warnedTexture2D === false ) { console.warn( "THREE.WebGLTextures.safeSetTexture2D: don't use render targets as textures. Use their .texture property instead." ); warnedTexture2D = true; } texture = texture.texture; } setTexture2D( texture, slot ); } function safeSetTextureCube( texture, slot ) { if ( texture && texture.isWebGLCubeRenderTarget ) { if ( warnedTextureCube === false ) { console.warn( "THREE.WebGLTextures.safeSetTextureCube: don't use cube render targets as textures. Use their .texture property instead." ); warnedTextureCube = true; } texture = texture.texture; } // currently relying on the fact that WebGLCubeRenderTarget.texture is a Texture and NOT a CubeTexture // TODO: unify these code paths if ( ( texture && texture.isCubeTexture ) || ( Array.isArray( texture.image ) && texture.image.length === 6 ) ) { // CompressedTexture can have Array in image :/ // this function alone should take care of cube textures setTextureCube( texture, slot ); } else { // assumed: texture property of THREE.WebGLCubeRenderTarget setTextureCubeDynamic( texture, slot ); } } // this.allocateTextureUnit = allocateTextureUnit; this.resetTextureUnits = resetTextureUnits; this.setTexture2D = setTexture2D; this.setTexture2DArray = setTexture2DArray; this.setTexture3D = setTexture3D; this.setTextureCube = setTextureCube; this.setTextureCubeDynamic = setTextureCubeDynamic; this.setupRenderTarget = setupRenderTarget; this.updateRenderTargetMipmap = updateRenderTargetMipmap; this.updateMultisampleRenderTarget = updateMultisampleRenderTarget; this.safeSetTexture2D = safeSetTexture2D; this.safeSetTextureCube = safeSetTextureCube; } /** * @author thespite / http://www.twitter.com/thespite */ function WebGLUtils( gl, extensions, capabilities ) { var isWebGL2 = capabilities.isWebGL2; function convert( p ) { var extension; if ( p === UnsignedByteType ) { return 5121; } if ( p === UnsignedShort4444Type ) { return 32819; } if ( p === UnsignedShort5551Type ) { return 32820; } if ( p === UnsignedShort565Type ) { return 33635; } if ( p === ByteType ) { return 5120; } if ( p === ShortType ) { return 5122; } if ( p === UnsignedShortType ) { return 5123; } if ( p === IntType ) { return 5124; } if ( p === UnsignedIntType ) { return 5125; } if ( p === FloatType ) { return 5126; } if ( p === HalfFloatType ) { if ( isWebGL2 ) { return 5131; } extension = extensions.get( 'OES_texture_half_float' ); if ( extension !== null ) { return extension.HALF_FLOAT_OES; } else { return null; } } if ( p === AlphaFormat ) { return 6406; } if ( p === RGBFormat ) { return 6407; } if ( p === RGBAFormat ) { return 6408; } if ( p === LuminanceFormat ) { return 6409; } if ( p === LuminanceAlphaFormat ) { return 6410; } if ( p === DepthFormat ) { return 6402; } if ( p === DepthStencilFormat ) { return 34041; } if ( p === RedFormat ) { return 6403; } // WebGL2 formats. if ( p === RedIntegerFormat ) { return 36244; } if ( p === RGFormat ) { return 33319; } if ( p === RGIntegerFormat ) { return 33320; } if ( p === RGBIntegerFormat ) { return 36248; } if ( p === RGBAIntegerFormat ) { return 36249; } if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) { extension = extensions.get( 'WEBGL_compressed_texture_s3tc' ); if ( extension !== null ) { if ( p === RGB_S3TC_DXT1_Format ) { return extension.COMPRESSED_RGB_S3TC_DXT1_EXT; } if ( p === RGBA_S3TC_DXT1_Format ) { return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT; } if ( p === RGBA_S3TC_DXT3_Format ) { return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT; } if ( p === RGBA_S3TC_DXT5_Format ) { return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT; } } else { return null; } } if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) { extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' ); if ( extension !== null ) { if ( p === RGB_PVRTC_4BPPV1_Format ) { return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG; } if ( p === RGB_PVRTC_2BPPV1_Format ) { return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG; } if ( p === RGBA_PVRTC_4BPPV1_Format ) { return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG; } if ( p === RGBA_PVRTC_2BPPV1_Format ) { return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG; } } else { return null; } } if ( p === RGB_ETC1_Format ) { extension = extensions.get( 'WEBGL_compressed_texture_etc1' ); if ( extension !== null ) { return extension.COMPRESSED_RGB_ETC1_WEBGL; } else { return null; } } if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format || p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format || p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format || p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format || p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) { extension = extensions.get( 'WEBGL_compressed_texture_astc' ); if ( extension !== null ) { // TODO Complete? return p; } else { return null; } } if ( p === UnsignedInt248Type ) { if ( isWebGL2 ) { return 34042; } extension = extensions.get( 'WEBGL_depth_texture' ); if ( extension !== null ) { return extension.UNSIGNED_INT_24_8_WEBGL; } else { return null; } } } return { convert: convert }; } /** * @author fernandojsg / http://fernandojsg.com * @author Takahiro https://github.com/takahirox */ function WebGLMultiviewRenderTarget( width, height, numViews, options ) { WebGLRenderTarget.call( this, width, height, options ); this.depthBuffer = false; this.stencilBuffer = false; this.numViews = numViews; } WebGLMultiviewRenderTarget.prototype = Object.assign( Object.create( WebGLRenderTarget.prototype ), { constructor: WebGLMultiviewRenderTarget, isWebGLMultiviewRenderTarget: true, copy: function ( source ) { WebGLRenderTarget.prototype.copy.call( this, source ); this.numViews = source.numViews; return this; }, setNumViews: function ( numViews ) { if ( this.numViews !== numViews ) { this.numViews = numViews; this.dispose(); } return this; } } ); /** * @author fernandojsg / http://fernandojsg.com * @author Takahiro https://github.com/takahirox */ function WebGLMultiview( renderer, gl ) { var DEFAULT_NUMVIEWS = 2; var extensions = renderer.extensions; var properties = renderer.properties; var renderTarget, currentRenderTarget; var mat3, mat4, cameraArray, renderSize; var available; var maxNumViews = 0; // function isAvailable() { if ( available === undefined ) { var extension = extensions.get( 'OVR_multiview2' ); available = extension !== null && gl.getContextAttributes().antialias === false; if ( available ) { maxNumViews = gl.getParameter( extension.MAX_VIEWS_OVR ); renderTarget = new WebGLMultiviewRenderTarget( 0, 0, DEFAULT_NUMVIEWS ); renderSize = new Vector2(); mat4 = []; mat3 = []; cameraArray = []; for ( var i = 0; i < maxNumViews; i ++ ) { mat4[ i ] = new Matrix4(); mat3[ i ] = new Matrix3(); } } } return available; } function getCameraArray( camera ) { if ( camera.isArrayCamera ) { return camera.cameras; } cameraArray[ 0 ] = camera; return cameraArray; } function updateCameraProjectionMatricesUniform( camera, uniforms ) { var cameras = getCameraArray( camera ); for ( var i = 0; i < cameras.length; i ++ ) { mat4[ i ].copy( cameras[ i ].projectionMatrix ); } uniforms.setValue( gl, 'projectionMatrices', mat4 ); } function updateCameraViewMatricesUniform( camera, uniforms ) { var cameras = getCameraArray( camera ); for ( var i = 0; i < cameras.length; i ++ ) { mat4[ i ].copy( cameras[ i ].matrixWorldInverse ); } uniforms.setValue( gl, 'viewMatrices', mat4 ); } function updateObjectMatricesUniforms( object, camera, uniforms ) { var cameras = getCameraArray( camera ); for ( var i = 0; i < cameras.length; i ++ ) { mat4[ i ].multiplyMatrices( cameras[ i ].matrixWorldInverse, object.matrixWorld ); mat3[ i ].getNormalMatrix( mat4[ i ] ); } uniforms.setValue( gl, 'modelViewMatrices', mat4 ); uniforms.setValue( gl, 'normalMatrices', mat3 ); } function isMultiviewCompatible( camera ) { if ( camera.isArrayCamera === undefined ) { return true; } var cameras = camera.cameras; if ( cameras.length > maxNumViews ) { return false; } for ( var i = 1, il = cameras.length; i < il; i ++ ) { if ( cameras[ 0 ].viewport.z !== cameras[ i ].viewport.z || cameras[ 0 ].viewport.w !== cameras[ i ].viewport.w ) { return false; } } return true; } function resizeRenderTarget( camera ) { if ( currentRenderTarget ) { renderSize.set( currentRenderTarget.width, currentRenderTarget.height ); } else { renderer.getDrawingBufferSize( renderSize ); } if ( camera.isArrayCamera ) { var viewport = camera.cameras[ 0 ].viewport; renderTarget.setSize( viewport.z, viewport.w ); renderTarget.setNumViews( camera.cameras.length ); } else { renderTarget.setSize( renderSize.x, renderSize.y ); renderTarget.setNumViews( DEFAULT_NUMVIEWS ); } } function attachCamera( camera ) { if ( isMultiviewCompatible( camera ) === false ) { return; } currentRenderTarget = renderer.getRenderTarget(); resizeRenderTarget( camera ); renderer.setRenderTarget( renderTarget ); } function detachCamera( camera ) { if ( renderTarget !== renderer.getRenderTarget() ) { return; } renderer.setRenderTarget( currentRenderTarget ); flush( camera ); } function flush( camera ) { var srcRenderTarget = renderTarget; var numViews = srcRenderTarget.numViews; var srcFramebuffers = properties.get( srcRenderTarget ).__webglViewFramebuffers; var viewWidth = srcRenderTarget.width; var viewHeight = srcRenderTarget.height; if ( camera.isArrayCamera ) { for ( var i = 0; i < numViews; i ++ ) { var viewport = camera.cameras[ i ].viewport; var x1 = viewport.x; var y1 = viewport.y; var x2 = x1 + viewport.z; var y2 = y1 + viewport.w; gl.bindFramebuffer( 36008, srcFramebuffers[ i ] ); gl.blitFramebuffer( 0, 0, viewWidth, viewHeight, x1, y1, x2, y2, 16384, 9728 ); } } else { gl.bindFramebuffer( 36008, srcFramebuffers[ 0 ] ); gl.blitFramebuffer( 0, 0, viewWidth, viewHeight, 0, 0, renderSize.x, renderSize.y, 16384, 9728 ); } } this.isAvailable = isAvailable; this.attachCamera = attachCamera; this.detachCamera = detachCamera; this.updateCameraProjectionMatricesUniform = updateCameraProjectionMatricesUniform; this.updateCameraViewMatricesUniform = updateCameraViewMatricesUniform; this.updateObjectMatricesUniforms = updateObjectMatricesUniforms; } /** * @author mrdoob / http://mrdoob.com/ */ function ArrayCamera( array ) { PerspectiveCamera.call( this ); this.cameras = array || []; } ArrayCamera.prototype = Object.assign( Object.create( PerspectiveCamera.prototype ), { constructor: ArrayCamera, isArrayCamera: true } ); /** * @author mrdoob / http://mrdoob.com/ */ function Group() { Object3D.call( this ); this.type = 'Group'; } Group.prototype = Object.assign( Object.create( Object3D.prototype ), { constructor: Group, isGroup: true } ); /** * @author mrdoob / http://mrdoob.com/ */ function WebXRManager( renderer, gl ) { var scope = this; var session = null; // var framebufferScaleFactor = 1.0; var referenceSpace = null; var referenceSpaceType = 'local-floor'; var pose = null; var controllers = []; var inputSourcesMap = new Map(); // var cameraL = new PerspectiveCamera(); cameraL.layers.enable( 1 ); cameraL.viewport = new Vector4(); var cameraR = new PerspectiveCamera(); cameraR.layers.enable( 2 ); cameraR.viewport = new Vector4(); var cameraVR = new ArrayCamera( [ cameraL, cameraR ] ); cameraVR.layers.enable( 1 ); cameraVR.layers.enable( 2 ); var _currentDepthNear = null; var _currentDepthFar = null; // this.enabled = false; this.isPresenting = false; this.getController = function ( id ) { var controller = controllers[ id ]; if ( controller === undefined ) { controller = {}; controllers[ id ] = controller; } if ( controller.targetRay === undefined ) { controller.targetRay = new Group(); controller.targetRay.matrixAutoUpdate = false; controller.targetRay.visible = false; } return controller.targetRay; }; this.getControllerGrip = function ( id ) { var controller = controllers[ id ]; if ( controller === undefined ) { controller = {}; controllers[ id ] = controller; } if ( controller.grip === undefined ) { controller.grip = new Group(); controller.grip.matrixAutoUpdate = false; controller.grip.visible = false; } return controller.grip; }; // function onSessionEvent( event ) { var controller = inputSourcesMap.get( event.inputSource ); if ( controller ) { if ( controller.targetRay ) { controller.targetRay.dispatchEvent( { type: event.type } ); } if ( controller.grip ) { controller.grip.dispatchEvent( { type: event.type } ); } } } function onSessionEnd() { inputSourcesMap.forEach( function ( controller, inputSource ) { if ( controller.targetRay ) { controller.targetRay.dispatchEvent( { type: 'disconnected', data: inputSource } ); controller.targetRay.visible = false; } if ( controller.grip ) { controller.grip.dispatchEvent( { type: 'disconnected', data: inputSource } ); controller.grip.visible = false; } } ); inputSourcesMap.clear(); // renderer.setFramebuffer( null ); renderer.setRenderTarget( renderer.getRenderTarget() ); // Hack #15830 animation.stop(); scope.isPresenting = false; scope.dispatchEvent( { type: 'sessionend' } ); } function onRequestReferenceSpace( value ) { referenceSpace = value; animation.setContext( session ); animation.start(); scope.isPresenting = true; scope.dispatchEvent( { type: 'sessionstart' } ); } this.setFramebufferScaleFactor = function ( /* value */ ) { // framebufferScaleFactor = value; }; this.setReferenceSpaceType = function ( value ) { referenceSpaceType = value; }; this.getReferenceSpace = function () { return referenceSpace; }; this.getSession = function () { return session; }; this.setSession = function ( value ) { session = value; if ( session !== null ) { session.addEventListener( 'select', onSessionEvent ); session.addEventListener( 'selectstart', onSessionEvent ); session.addEventListener( 'selectend', onSessionEvent ); session.addEventListener( 'squeeze', onSessionEvent ); session.addEventListener( 'squeezestart', onSessionEvent ); session.addEventListener( 'squeezeend', onSessionEvent ); session.addEventListener( 'end', onSessionEnd ); var attributes = gl.getContextAttributes(); var layerInit = { antialias: attributes.antialias, alpha: attributes.alpha, depth: attributes.depth, stencil: attributes.stencil }; // eslint-disable-next-line no-undef var baseLayer = new XRWebGLLayer( session, gl, layerInit ); session.updateRenderState( { baseLayer: baseLayer } ); session.requestReferenceSpace( referenceSpaceType ).then( onRequestReferenceSpace ); // session.addEventListener( 'inputsourceschange', updateInputSources ); } }; function updateInputSources( event ) { var inputSources = session.inputSources; // Assign inputSources to available controllers for ( var i = 0; i < controllers.length; i ++ ) { inputSourcesMap.set( inputSources[ i ], controllers[ i ] ); } // Notify disconnected for ( var i = 0; i < event.removed.length; i ++ ) { var inputSource = event.removed[ i ]; var controller = inputSourcesMap.get( inputSource ); if ( controller ) { if ( controller.targetRay ) { controller.targetRay.dispatchEvent( { type: 'disconnected', data: inputSource } ); } if ( controller.grip ) { controller.grip.dispatchEvent( { type: 'disconnected', data: inputSource } ); } inputSourcesMap.delete( inputSource ); } } // Notify connected for ( var i = 0; i < event.added.length; i ++ ) { var inputSource = event.added[ i ]; var controller = inputSourcesMap.get( inputSource ); if ( controller ) { if ( controller.targetRay ) { controller.targetRay.dispatchEvent( { type: 'connected', data: inputSource } ); } if ( controller.grip ) { controller.grip.dispatchEvent( { type: 'connected', data: inputSource } ); } } } } // var cameraLPos = new Vector3(); var cameraRPos = new Vector3(); /** * @author jsantell / https://www.jsantell.com/ * * Assumes 2 cameras that are parallel and share an X-axis, and that * the cameras' projection and world matrices have already been set. * And that near and far planes are identical for both cameras. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765 */ function setProjectionFromUnion( camera, cameraL, cameraR ) { cameraLPos.setFromMatrixPosition( cameraL.matrixWorld ); cameraRPos.setFromMatrixPosition( cameraR.matrixWorld ); var ipd = cameraLPos.distanceTo( cameraRPos ); var projL = cameraL.projectionMatrix.elements; var projR = cameraR.projectionMatrix.elements; // VR systems will have identical far and near planes, and // most likely identical top and bottom frustum extents. // Use the left camera for these values. var near = projL[ 14 ] / ( projL[ 10 ] - 1 ); var far = projL[ 14 ] / ( projL[ 10 ] + 1 ); var topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ]; var bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ]; var leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ]; var rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ]; var left = near * leftFov; var right = near * rightFov; // Calculate the new camera's position offset from the // left camera. xOffset should be roughly half `ipd`. var zOffset = ipd / ( - leftFov + rightFov ); var xOffset = zOffset * - leftFov; // TODO: Better way to apply this offset? cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale ); camera.translateX( xOffset ); camera.translateZ( zOffset ); camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale ); camera.matrixWorldInverse.getInverse( camera.matrixWorld ); // Find the union of the frustum values of the cameras and scale // the values so that the near plane's position does not change in world space, // although must now be relative to the new union camera. var near2 = near + zOffset; var far2 = far + zOffset; var left2 = left - xOffset; var right2 = right + ( ipd - xOffset ); var top2 = topFov * far / far2 * near2; var bottom2 = bottomFov * far / far2 * near2; camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 ); } function updateCamera( camera, parent ) { if ( parent === null ) { camera.matrixWorld.copy( camera.matrix ); } else { camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix ); } camera.matrixWorldInverse.getInverse( camera.matrixWorld ); } this.getCamera = function ( camera ) { cameraVR.near = cameraR.near = cameraL.near = camera.near; cameraVR.far = cameraR.far = cameraL.far = camera.far; if ( _currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far ) { // Note that the new renderState won't apply until the next frame. See #18320 session.updateRenderState( { depthNear: cameraVR.near, depthFar: cameraVR.far } ); _currentDepthNear = cameraVR.near; _currentDepthFar = cameraVR.far; } var parent = camera.parent; var cameras = cameraVR.cameras; updateCamera( cameraVR, parent ); for ( var i = 0; i < cameras.length; i ++ ) { updateCamera( cameras[ i ], parent ); } // update camera and its children camera.matrixWorld.copy( cameraVR.matrixWorld ); var children = camera.children; for ( var i = 0, l = children.length; i < l; i ++ ) { children[ i ].updateMatrixWorld( true ); } setProjectionFromUnion( cameraVR, cameraL, cameraR ); return cameraVR; }; // Animation Loop var onAnimationFrameCallback = null; function onAnimationFrame( time, frame ) { pose = frame.getViewerPose( referenceSpace ); if ( pose !== null ) { var views = pose.views; var baseLayer = session.renderState.baseLayer; renderer.setFramebuffer( baseLayer.framebuffer ); for ( var i = 0; i < views.length; i ++ ) { var view = views[ i ]; var viewport = baseLayer.getViewport( view ); var camera = cameraVR.cameras[ i ]; camera.matrix.fromArray( view.transform.matrix ); camera.projectionMatrix.fromArray( view.projectionMatrix ); camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height ); if ( i === 0 ) { cameraVR.matrix.copy( camera.matrix ); } } } // var inputSources = session.inputSources; for ( var i = 0; i < controllers.length; i ++ ) { var controller = controllers[ i ]; var inputSource = inputSources[ i ]; var inputPose = null; var gripPose = null; if ( inputSource ) { if ( controller.targetRay ) { inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace ); if ( inputPose !== null ) { controller.targetRay.matrix.fromArray( inputPose.transform.matrix ); controller.targetRay.matrix.decompose( controller.targetRay.position, controller.targetRay.rotation, controller.targetRay.scale ); } } if ( controller.grip && inputSource.gripSpace ) { gripPose = frame.getPose( inputSource.gripSpace, referenceSpace ); if ( gripPose !== null ) { controller.grip.matrix.fromArray( gripPose.transform.matrix ); controller.grip.matrix.decompose( controller.grip.position, controller.grip.rotation, controller.grip.scale ); } } } if ( controller.targetRay ) { controller.targetRay.visible = inputPose !== null; } if ( controller.grip ) { controller.grip.visible = gripPose !== null; } } if ( onAnimationFrameCallback ) { onAnimationFrameCallback( time, frame ); } } var animation = new WebGLAnimation(); animation.setAnimationLoop( onAnimationFrame ); this.setAnimationLoop = function ( callback ) { onAnimationFrameCallback = callback; }; this.dispose = function () {}; } Object.assign( WebXRManager.prototype, EventDispatcher.prototype ); /** * @author supereggbert / http://www.paulbrunt.co.uk/ * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ * @author szimek / https://github.com/szimek/ * @author tschw */ function WebGLRenderer( parameters ) { parameters = parameters || {}; var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ), _context = parameters.context !== undefined ? parameters.context : null, _alpha = parameters.alpha !== undefined ? parameters.alpha : false, _depth = parameters.depth !== undefined ? parameters.depth : true, _stencil = parameters.stencil !== undefined ? parameters.stencil : true, _antialias = parameters.antialias !== undefined ? parameters.antialias : false, _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true, _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false, _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default', _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false; var currentRenderList = null; var currentRenderState = null; // public properties this.domElement = _canvas; // Debug configuration container this.debug = { /** * Enables error checking and reporting when shader programs are being compiled * @type {boolean} */ checkShaderErrors: true }; // clearing this.autoClear = true; this.autoClearColor = true; this.autoClearDepth = true; this.autoClearStencil = true; // scene graph this.sortObjects = true; // user-defined clipping this.clippingPlanes = []; this.localClippingEnabled = false; // physically based shading this.gammaFactor = 2.0; // for backwards compatibility this.outputEncoding = LinearEncoding; // physical lights this.physicallyCorrectLights = false; // tone mapping this.toneMapping = LinearToneMapping; this.toneMappingExposure = 1.0; this.toneMappingWhitePoint = 1.0; // morphs this.maxMorphTargets = 8; this.maxMorphNormals = 4; // internal properties var _this = this, _isContextLost = false, // internal state cache _framebuffer = null, _currentActiveCubeFace = 0, _currentActiveMipmapLevel = 0, _currentRenderTarget = null, _currentFramebuffer = null, _currentMaterialId = - 1, // geometry and program caching _currentGeometryProgram = { geometry: null, program: null, wireframe: false }, _currentCamera = null, _currentArrayCamera = null, _currentViewport = new Vector4(), _currentScissor = new Vector4(), _currentScissorTest = null, // _width = _canvas.width, _height = _canvas.height, _pixelRatio = 1, _opaqueSort = null, _transparentSort = null, _viewport = new Vector4( 0, 0, _width, _height ), _scissor = new Vector4( 0, 0, _width, _height ), _scissorTest = false, // frustum _frustum = new Frustum(), // clipping _clipping = new WebGLClipping(), _clippingEnabled = false, _localClippingEnabled = false, // camera matrices cache _projScreenMatrix = new Matrix4(), _vector3 = new Vector3(); function getTargetPixelRatio() { return _currentRenderTarget === null ? _pixelRatio : 1; } // initialize var _gl; try { var contextAttributes = { alpha: _alpha, depth: _depth, stencil: _stencil, antialias: _antialias, premultipliedAlpha: _premultipliedAlpha, preserveDrawingBuffer: _preserveDrawingBuffer, powerPreference: _powerPreference, failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat, xrCompatible: true }; // event listeners must be registered before WebGL context is created, see #12753 _canvas.addEventListener( 'webglcontextlost', onContextLost, false ); _canvas.addEventListener( 'webglcontextrestored', onContextRestore, false ); _gl = _context || _canvas.getContext( 'webgl', contextAttributes ) || _canvas.getContext( 'experimental-webgl', contextAttributes ); if ( _gl === null ) { if ( _canvas.getContext( 'webgl' ) !== null ) { throw new Error( 'Error creating WebGL context with your selected attributes.' ); } else { throw new Error( 'Error creating WebGL context.' ); } } // Some experimental-webgl implementations do not have getShaderPrecisionFormat if ( _gl.getShaderPrecisionFormat === undefined ) { _gl.getShaderPrecisionFormat = function () { return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 }; }; } } catch ( error ) { console.error( 'THREE.WebGLRenderer: ' + error.message ); throw error; } var extensions, capabilities, state, info; var properties, textures, attributes, geometries, objects; var programCache, renderLists, renderStates; var background, morphtargets, bufferRenderer, indexedBufferRenderer; var utils; function initGLContext() { extensions = new WebGLExtensions( _gl ); capabilities = new WebGLCapabilities( _gl, extensions, parameters ); if ( capabilities.isWebGL2 === false ) { extensions.get( 'WEBGL_depth_texture' ); extensions.get( 'OES_texture_float' ); extensions.get( 'OES_texture_half_float' ); extensions.get( 'OES_texture_half_float_linear' ); extensions.get( 'OES_standard_derivatives' ); extensions.get( 'OES_element_index_uint' ); extensions.get( 'ANGLE_instanced_arrays' ); } extensions.get( 'OES_texture_float_linear' ); utils = new WebGLUtils( _gl, extensions, capabilities ); state = new WebGLState( _gl, extensions, capabilities ); state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() ); state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() ); info = new WebGLInfo( _gl ); properties = new WebGLProperties(); textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ); attributes = new WebGLAttributes( _gl, capabilities ); geometries = new WebGLGeometries( _gl, attributes, info ); objects = new WebGLObjects( _gl, geometries, attributes, info ); morphtargets = new WebGLMorphtargets( _gl ); programCache = new WebGLPrograms( _this, extensions, capabilities ); renderLists = new WebGLRenderLists(); renderStates = new WebGLRenderStates(); background = new WebGLBackground( _this, state, objects, _premultipliedAlpha ); bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info, capabilities ); indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info, capabilities ); info.programs = programCache.programs; _this.capabilities = capabilities; _this.extensions = extensions; _this.properties = properties; _this.renderLists = renderLists; _this.state = state; _this.info = info; } initGLContext(); // xr var xr = new WebXRManager( _this, _gl ); this.xr = xr; // Multiview var multiview = new WebGLMultiview( _this, _gl ); // shadow map var shadowMap = new WebGLShadowMap( _this, objects, capabilities.maxTextureSize ); this.shadowMap = shadowMap; // API this.getContext = function () { return _gl; }; this.getContextAttributes = function () { return _gl.getContextAttributes(); }; this.forceContextLoss = function () { var extension = extensions.get( 'WEBGL_lose_context' ); if ( extension ) { extension.loseContext(); } }; this.forceContextRestore = function () { var extension = extensions.get( 'WEBGL_lose_context' ); if ( extension ) { extension.restoreContext(); } }; this.getPixelRatio = function () { return _pixelRatio; }; this.setPixelRatio = function ( value ) { if ( value === undefined ) { return; } _pixelRatio = value; this.setSize( _width, _height, false ); }; this.getSize = function ( target ) { if ( target === undefined ) { console.warn( 'WebGLRenderer: .getsize() now requires a Vector2 as an argument' ); target = new Vector2(); } return target.set( _width, _height ); }; this.setSize = function ( width, height, updateStyle ) { if ( xr.isPresenting ) { console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' ); return; } _width = width; _height = height; _canvas.width = Math.floor( width * _pixelRatio ); _canvas.height = Math.floor( height * _pixelRatio ); if ( updateStyle !== false ) { _canvas.style.width = width + 'px'; _canvas.style.height = height + 'px'; } this.setViewport( 0, 0, width, height ); }; this.getDrawingBufferSize = function ( target ) { if ( target === undefined ) { console.warn( 'WebGLRenderer: .getdrawingBufferSize() now requires a Vector2 as an argument' ); target = new Vector2(); } return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor(); }; this.setDrawingBufferSize = function ( width, height, pixelRatio ) { _width = width; _height = height; _pixelRatio = pixelRatio; _canvas.width = Math.floor( width * pixelRatio ); _canvas.height = Math.floor( height * pixelRatio ); this.setViewport( 0, 0, width, height ); }; this.getCurrentViewport = function ( target ) { if ( target === undefined ) { console.warn( 'WebGLRenderer: .getCurrentViewport() now requires a Vector4 as an argument' ); target = new Vector4(); } return target.copy( _currentViewport ); }; this.getViewport = function ( target ) { return target.copy( _viewport ); }; this.setViewport = function ( x, y, width, height ) { if ( x.isVector4 ) { _viewport.set( x.x, x.y, x.z, x.w ); } else { _viewport.set( x, y, width, height ); } state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() ); }; this.getScissor = function ( target ) { return target.copy( _scissor ); }; this.setScissor = function ( x, y, width, height ) { if ( x.isVector4 ) { _scissor.set( x.x, x.y, x.z, x.w ); } else { _scissor.set( x, y, width, height ); } state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() ); }; this.getScissorTest = function () { return _scissorTest; }; this.setScissorTest = function ( boolean ) { state.setScissorTest( _scissorTest = boolean ); }; this.setOpaqueSort = function ( method ) { _opaqueSort = method; }; this.setTransparentSort = function ( method ) { _transparentSort = method; }; // Clearing this.getClearColor = function () { return background.getClearColor(); }; this.setClearColor = function () { background.setClearColor.apply( background, arguments ); }; this.getClearAlpha = function () { return background.getClearAlpha(); }; this.setClearAlpha = function () { background.setClearAlpha.apply( background, arguments ); }; this.clear = function ( color, depth, stencil ) { var bits = 0; if ( color === undefined || color ) { bits |= 16384; } if ( depth === undefined || depth ) { bits |= 256; } if ( stencil === undefined || stencil ) { bits |= 1024; } _gl.clear( bits ); }; this.clearColor = function () { this.clear( true, false, false ); }; this.clearDepth = function () { this.clear( false, true, false ); }; this.clearStencil = function () { this.clear( false, false, true ); }; // this.dispose = function () { _canvas.removeEventListener( 'webglcontextlost', onContextLost, false ); _canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false ); renderLists.dispose(); renderStates.dispose(); properties.dispose(); objects.dispose(); xr.dispose(); animation.stop(); }; // Events function onContextLost( event ) { event.preventDefault(); console.log( 'THREE.WebGLRenderer: Context Lost.' ); _isContextLost = true; } function onContextRestore( /* event */ ) { console.log( 'THREE.WebGLRenderer: Context Restored.' ); _isContextLost = false; initGLContext(); } function onMaterialDispose( event ) { var material = event.target; material.removeEventListener( 'dispose', onMaterialDispose ); deallocateMaterial( material ); } // Buffer deallocation function deallocateMaterial( material ) { releaseMaterialProgramReference( material ); properties.remove( material ); } function releaseMaterialProgramReference( material ) { var programInfo = properties.get( material ).program; material.program = undefined; if ( programInfo !== undefined ) { programCache.releaseProgram( programInfo ); } } // Buffer rendering function renderObjectImmediate( object, program ) { object.render( function ( object ) { _this.renderBufferImmediate( object, program ); } ); } this.renderBufferImmediate = function ( object, program ) { state.initAttributes(); var buffers = properties.get( object ); if ( object.hasPositions && ! buffers.position ) { buffers.position = _gl.createBuffer(); } if ( object.hasNormals && ! buffers.normal ) { buffers.normal = _gl.createBuffer(); } if ( object.hasUvs && ! buffers.uv ) { buffers.uv = _gl.createBuffer(); } if ( object.hasColors && ! buffers.color ) { buffers.color = _gl.createBuffer(); } var programAttributes = program.getAttributes(); if ( object.hasPositions ) { _gl.bindBuffer( 34962, buffers.position ); _gl.bufferData( 34962, object.positionArray, 35048 ); state.enableAttribute( programAttributes.position ); _gl.vertexAttribPointer( programAttributes.position, 3, 5126, false, 0, 0 ); } if ( object.hasNormals ) { _gl.bindBuffer( 34962, buffers.normal ); _gl.bufferData( 34962, object.normalArray, 35048 ); state.enableAttribute( programAttributes.normal ); _gl.vertexAttribPointer( programAttributes.normal, 3, 5126, false, 0, 0 ); } if ( object.hasUvs ) { _gl.bindBuffer( 34962, buffers.uv ); _gl.bufferData( 34962, object.uvArray, 35048 ); state.enableAttribute( programAttributes.uv ); _gl.vertexAttribPointer( programAttributes.uv, 2, 5126, false, 0, 0 ); } if ( object.hasColors ) { _gl.bindBuffer( 34962, buffers.color ); _gl.bufferData( 34962, object.colorArray, 35048 ); state.enableAttribute( programAttributes.color ); _gl.vertexAttribPointer( programAttributes.color, 3, 5126, false, 0, 0 ); } state.disableUnusedAttributes(); _gl.drawArrays( 4, 0, object.count ); object.count = 0; }; var tempScene = new Scene(); this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) { if ( scene === null ) { scene = tempScene; } // renderBufferDirect second parameter used to be fog (could be null) var frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 ); var program = setProgram( camera, scene, material, object ); state.setMaterial( material, frontFaceCW ); var updateBuffers = false; if ( _currentGeometryProgram.geometry !== geometry.id || _currentGeometryProgram.program !== program.id || _currentGeometryProgram.wireframe !== ( material.wireframe === true ) ) { _currentGeometryProgram.geometry = geometry.id; _currentGeometryProgram.program = program.id; _currentGeometryProgram.wireframe = material.wireframe === true; updateBuffers = true; } if ( material.morphTargets || material.morphNormals ) { morphtargets.update( object, geometry, material, program ); updateBuffers = true; } // var index = geometry.index; var position = geometry.attributes.position; // if ( index === null ) { if ( position === undefined || position.count === 0 ) { return; } } else if ( index.count === 0 ) { return; } // var rangeFactor = 1; if ( material.wireframe === true ) { index = geometries.getWireframeAttribute( geometry ); rangeFactor = 2; } var attribute; var renderer = bufferRenderer; if ( index !== null ) { attribute = attributes.get( index ); renderer = indexedBufferRenderer; renderer.setIndex( attribute ); } if ( updateBuffers ) { setupVertexAttributes( object, geometry, material, program ); if ( index !== null ) { _gl.bindBuffer( 34963, attribute.buffer ); } } // var dataCount = ( index !== null ) ? index.count : position.count; var rangeStart = geometry.drawRange.start * rangeFactor; var rangeCount = geometry.drawRange.count * rangeFactor; var groupStart = group !== null ? group.start * rangeFactor : 0; var groupCount = group !== null ? group.count * rangeFactor : Infinity; var drawStart = Math.max( rangeStart, groupStart ); var drawEnd = Math.min( dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1; var drawCount = Math.max( 0, drawEnd - drawStart + 1 ); if ( drawCount === 0 ) { return; } // if ( object.isMesh ) { if ( material.wireframe === true ) { state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() ); renderer.setMode( 1 ); } else { renderer.setMode( 4 ); } } else if ( object.isLine ) { var lineWidth = material.linewidth; if ( lineWidth === undefined ) { lineWidth = 1; } // Not using Line*Material state.setLineWidth( lineWidth * getTargetPixelRatio() ); if ( object.isLineSegments ) { renderer.setMode( 1 ); } else if ( object.isLineLoop ) { renderer.setMode( 2 ); } else { renderer.setMode( 3 ); } } else if ( object.isPoints ) { renderer.setMode( 0 ); } else if ( object.isSprite ) { renderer.setMode( 4 ); } if ( object.isInstancedMesh ) { renderer.renderInstances( geometry, drawStart, drawCount, object.count ); } else if ( geometry.isInstancedBufferGeometry ) { renderer.renderInstances( geometry, drawStart, drawCount, geometry.maxInstancedCount ); } else { renderer.render( drawStart, drawCount ); } }; function setupVertexAttributes( object, geometry, material, program ) { if ( capabilities.isWebGL2 === false && ( object.isInstancedMesh || geometry.isInstancedBufferGeometry ) ) { if ( extensions.get( 'ANGLE_instanced_arrays' ) === null ) { return; } } state.initAttributes(); var geometryAttributes = geometry.attributes; var programAttributes = program.getAttributes(); var materialDefaultAttributeValues = material.defaultAttributeValues; for ( var name in programAttributes ) { var programAttribute = programAttributes[ name ]; if ( programAttribute >= 0 ) { var geometryAttribute = geometryAttributes[ name ]; if ( geometryAttribute !== undefined ) { var normalized = geometryAttribute.normalized; var size = geometryAttribute.itemSize; var attribute = attributes.get( geometryAttribute ); // TODO Attribute may not be available on context restore if ( attribute === undefined ) { continue; } var buffer = attribute.buffer; var type = attribute.type; var bytesPerElement = attribute.bytesPerElement; if ( geometryAttribute.isInterleavedBufferAttribute ) { var data = geometryAttribute.data; var stride = data.stride; var offset = geometryAttribute.offset; if ( data && data.isInstancedInterleavedBuffer ) { state.enableAttributeAndDivisor( programAttribute, data.meshPerAttribute ); if ( geometry.maxInstancedCount === undefined ) { geometry.maxInstancedCount = data.meshPerAttribute * data.count; } } else { state.enableAttribute( programAttribute ); } _gl.bindBuffer( 34962, buffer ); _gl.vertexAttribPointer( programAttribute, size, type, normalized, stride * bytesPerElement, offset * bytesPerElement ); } else { if ( geometryAttribute.isInstancedBufferAttribute ) { state.enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute ); if ( geometry.maxInstancedCount === undefined ) { geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count; } } else { state.enableAttribute( programAttribute ); } _gl.bindBuffer( 34962, buffer ); _gl.vertexAttribPointer( programAttribute, size, type, normalized, 0, 0 ); } } else if ( name === 'instanceMatrix' ) { var attribute = attributes.get( object.instanceMatrix ); // TODO Attribute may not be available on context restore if ( attribute === undefined ) { continue; } var buffer = attribute.buffer; var type = attribute.type; state.enableAttributeAndDivisor( programAttribute + 0, 1 ); state.enableAttributeAndDivisor( programAttribute + 1, 1 ); state.enableAttributeAndDivisor( programAttribute + 2, 1 ); state.enableAttributeAndDivisor( programAttribute + 3, 1 ); _gl.bindBuffer( 34962, buffer ); _gl.vertexAttribPointer( programAttribute + 0, 4, type, false, 64, 0 ); _gl.vertexAttribPointer( programAttribute + 1, 4, type, false, 64, 16 ); _gl.vertexAttribPointer( programAttribute + 2, 4, type, false, 64, 32 ); _gl.vertexAttribPointer( programAttribute + 3, 4, type, false, 64, 48 ); } else if ( materialDefaultAttributeValues !== undefined ) { var value = materialDefaultAttributeValues[ name ]; if ( value !== undefined ) { switch ( value.length ) { case 2: _gl.vertexAttrib2fv( programAttribute, value ); break; case 3: _gl.vertexAttrib3fv( programAttribute, value ); break; case 4: _gl.vertexAttrib4fv( programAttribute, value ); break; default: _gl.vertexAttrib1fv( programAttribute, value ); } } } } } state.disableUnusedAttributes(); } // Compile this.compile = function ( scene, camera ) { currentRenderState = renderStates.get( scene, camera ); currentRenderState.init(); scene.traverse( function ( object ) { if ( object.isLight ) { currentRenderState.pushLight( object ); if ( object.castShadow ) { currentRenderState.pushShadow( object ); } } } ); currentRenderState.setupLights( camera ); var compiled = {}; scene.traverse( function ( object ) { if ( object.material ) { if ( Array.isArray( object.material ) ) { for ( var i = 0; i < object.material.length; i ++ ) { if ( object.material[ i ].uuid in compiled === false ) { initMaterial( object.material[ i ], scene, object ); compiled[ object.material[ i ].uuid ] = true; } } } else if ( object.material.uuid in compiled === false ) { initMaterial( object.material, scene, object ); compiled[ object.material.uuid ] = true; } } } ); }; // Animation Loop var onAnimationFrameCallback = null; function onAnimationFrame( time ) { if ( xr.isPresenting ) { return; } if ( onAnimationFrameCallback ) { onAnimationFrameCallback( time ); } } var animation = new WebGLAnimation(); animation.setAnimationLoop( onAnimationFrame ); if ( typeof window !== 'undefined' ) { animation.setContext( window ); } this.setAnimationLoop = function ( callback ) { onAnimationFrameCallback = callback; xr.setAnimationLoop( callback ); animation.start(); }; // Rendering this.render = function ( scene, camera ) { var renderTarget, forceClear; if ( arguments[ 2 ] !== undefined ) { console.warn( 'THREE.WebGLRenderer.render(): the renderTarget argument has been removed. Use .setRenderTarget() instead.' ); renderTarget = arguments[ 2 ]; } if ( arguments[ 3 ] !== undefined ) { console.warn( 'THREE.WebGLRenderer.render(): the forceClear argument has been removed. Use .clear() instead.' ); forceClear = arguments[ 3 ]; } if ( ! ( camera && camera.isCamera ) ) { console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' ); return; } if ( _isContextLost ) { return; } // reset caching for this frame _currentGeometryProgram.geometry = null; _currentGeometryProgram.program = null; _currentGeometryProgram.wireframe = false; _currentMaterialId = - 1; _currentCamera = null; // update scene graph if ( scene.autoUpdate === true ) { scene.updateMatrixWorld(); } // update camera matrices and frustum if ( camera.parent === null ) { camera.updateMatrixWorld(); } if ( xr.enabled && xr.isPresenting ) { camera = xr.getCamera( camera ); } // currentRenderState = renderStates.get( scene, camera ); currentRenderState.init(); scene.onBeforeRender( _this, scene, camera, renderTarget || _currentRenderTarget ); _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse ); _frustum.setFromProjectionMatrix( _projScreenMatrix ); _localClippingEnabled = this.localClippingEnabled; _clippingEnabled = _clipping.init( this.clippingPlanes, _localClippingEnabled, camera ); currentRenderList = renderLists.get( scene, camera ); currentRenderList.init(); projectObject( scene, camera, 0, _this.sortObjects ); if ( _this.sortObjects === true ) { currentRenderList.sort( _opaqueSort, _transparentSort ); } // if ( _clippingEnabled ) { _clipping.beginShadows(); } var shadowsArray = currentRenderState.state.shadowsArray; shadowMap.render( shadowsArray, scene, camera ); currentRenderState.setupLights( camera ); if ( _clippingEnabled ) { _clipping.endShadows(); } // if ( this.info.autoReset ) { this.info.reset(); } if ( renderTarget !== undefined ) { this.setRenderTarget( renderTarget ); } if ( xr.enabled && multiview.isAvailable() ) { multiview.attachCamera( camera ); } // background.render( currentRenderList, scene, camera, forceClear ); // render scene var opaqueObjects = currentRenderList.opaque; var transparentObjects = currentRenderList.transparent; if ( scene.overrideMaterial ) { var overrideMaterial = scene.overrideMaterial; if ( opaqueObjects.length ) { renderObjects( opaqueObjects, scene, camera, overrideMaterial ); } if ( transparentObjects.length ) { renderObjects( transparentObjects, scene, camera, overrideMaterial ); } } else { // opaque pass (front-to-back order) if ( opaqueObjects.length ) { renderObjects( opaqueObjects, scene, camera ); } // transparent pass (back-to-front order) if ( transparentObjects.length ) { renderObjects( transparentObjects, scene, camera ); } } // scene.onAfterRender( _this, scene, camera ); // if ( _currentRenderTarget !== null ) { // Generate mipmap if we're using any kind of mipmap filtering textures.updateRenderTargetMipmap( _currentRenderTarget ); // resolve multisample renderbuffers to a single-sample texture if necessary textures.updateMultisampleRenderTarget( _currentRenderTarget ); } // Ensure depth buffer writing is enabled so it can be cleared on next render state.buffers.depth.setTest( true ); state.buffers.depth.setMask( true ); state.buffers.color.setMask( true ); state.setPolygonOffset( false ); if ( xr.enabled ) { if ( multiview.isAvailable() ) { multiview.detachCamera( camera ); } } // _gl.finish(); currentRenderList = null; currentRenderState = null; }; function projectObject( object, camera, groupOrder, sortObjects ) { if ( object.visible === false ) { return; } var visible = object.layers.test( camera.layers ); if ( visible ) { if ( object.isGroup ) { groupOrder = object.renderOrder; } else if ( object.isLOD ) { if ( object.autoUpdate === true ) { object.update( camera ); } } else if ( object.isLight ) { currentRenderState.pushLight( object ); if ( object.castShadow ) { currentRenderState.pushShadow( object ); } } else if ( object.isSprite ) { if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) { if ( sortObjects ) { _vector3.setFromMatrixPosition( object.matrixWorld ) .applyMatrix4( _projScreenMatrix ); } var geometry = objects.update( object ); var material = object.material; if ( material.visible ) { currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null ); } } } else if ( object.isImmediateRenderObject ) { if ( sortObjects ) { _vector3.setFromMatrixPosition( object.matrixWorld ) .applyMatrix4( _projScreenMatrix ); } currentRenderList.push( object, null, object.material, groupOrder, _vector3.z, null ); } else if ( object.isMesh || object.isLine || object.isPoints ) { if ( object.isSkinnedMesh ) { // update skeleton only once in a frame if ( object.skeleton.frame !== info.render.frame ) { object.skeleton.update(); object.skeleton.frame = info.render.frame; } } if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) { if ( sortObjects ) { _vector3.setFromMatrixPosition( object.matrixWorld ) .applyMatrix4( _projScreenMatrix ); } var geometry = objects.update( object ); var material = object.material; if ( Array.isArray( material ) ) { var groups = geometry.groups; for ( var i = 0, l = groups.length; i < l; i ++ ) { var group = groups[ i ]; var groupMaterial = material[ group.materialIndex ]; if ( groupMaterial && groupMaterial.visible ) { currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group ); } } } else if ( material.visible ) { currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null ); } } } } var children = object.children; for ( var i = 0, l = children.length; i < l; i ++ ) { projectObject( children[ i ], camera, groupOrder, sortObjects ); } } function renderObjects( renderList, scene, camera, overrideMaterial ) { for ( var i = 0, l = renderList.length; i < l; i ++ ) { var renderItem = renderList[ i ]; var object = renderItem.object; var geometry = renderItem.geometry; var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial; var group = renderItem.group; if ( camera.isArrayCamera ) { _currentArrayCamera = camera; if ( xr.enabled && multiview.isAvailable() ) { renderObject( object, scene, camera, geometry, material, group ); } else { var cameras = camera.cameras; for ( var j = 0, jl = cameras.length; j < jl; j ++ ) { var camera2 = cameras[ j ]; if ( object.layers.test( camera2.layers ) ) { state.viewport( _currentViewport.copy( camera2.viewport ) ); currentRenderState.setupLights( camera2 ); renderObject( object, scene, camera2, geometry, material, group ); } } } } else { _currentArrayCamera = null; renderObject( object, scene, camera, geometry, material, group ); } } } function renderObject( object, scene, camera, geometry, material, group ) { object.onBeforeRender( _this, scene, camera, geometry, material, group ); currentRenderState = renderStates.get( scene, _currentArrayCamera || camera ); object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld ); object.normalMatrix.getNormalMatrix( object.modelViewMatrix ); if ( object.isImmediateRenderObject ) { var program = setProgram( camera, scene, material, object ); state.setMaterial( material ); _currentGeometryProgram.geometry = null; _currentGeometryProgram.program = null; _currentGeometryProgram.wireframe = false; renderObjectImmediate( object, program ); } else { _this.renderBufferDirect( camera, scene, geometry, material, object, group ); } object.onAfterRender( _this, scene, camera, geometry, material, group ); currentRenderState = renderStates.get( scene, _currentArrayCamera || camera ); } function initMaterial( material, scene, object ) { var materialProperties = properties.get( material ); var lights = currentRenderState.state.lights; var shadowsArray = currentRenderState.state.shadowsArray; var lightsStateVersion = lights.state.version; var parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, _clipping.numPlanes, _clipping.numIntersection, object ); var programCacheKey = programCache.getProgramCacheKey( parameters ); var program = materialProperties.program; var programChange = true; if ( program === undefined ) { // new material material.addEventListener( 'dispose', onMaterialDispose ); } else if ( program.cacheKey !== programCacheKey ) { // changed glsl or parameters releaseMaterialProgramReference( material ); } else if ( materialProperties.lightsStateVersion !== lightsStateVersion ) { materialProperties.lightsStateVersion = lightsStateVersion; programChange = false; } else if ( parameters.shaderID !== undefined ) { // same glsl and uniform list return; } else { // only rebuild uniform list programChange = false; } if ( programChange ) { program = programCache.acquireProgram( parameters, programCacheKey ); materialProperties.program = program; materialProperties.uniforms = parameters.uniforms; materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null; materialProperties.outputEncoding = _this.outputEncoding; material.program = program; } var programAttributes = program.getAttributes(); if ( material.morphTargets ) { material.numSupportedMorphTargets = 0; for ( var i = 0; i < _this.maxMorphTargets; i ++ ) { if ( programAttributes[ 'morphTarget' + i ] >= 0 ) { material.numSupportedMorphTargets ++; } } } if ( material.morphNormals ) { material.numSupportedMorphNormals = 0; for ( var i = 0; i < _this.maxMorphNormals; i ++ ) { if ( programAttributes[ 'morphNormal' + i ] >= 0 ) { material.numSupportedMorphNormals ++; } } } var uniforms = materialProperties.uniforms; if ( ! material.isShaderMaterial && ! material.isRawShaderMaterial || material.clipping === true ) { materialProperties.numClippingPlanes = _clipping.numPlanes; materialProperties.numIntersection = _clipping.numIntersection; uniforms.clippingPlanes = _clipping.uniform; } materialProperties.fog = scene.fog; // store the light setup it was created for materialProperties.needsLights = materialNeedsLights( material ); materialProperties.lightsStateVersion = lightsStateVersion; if ( materialProperties.needsLights ) { // wire up the material to this renderer's lighting state uniforms.ambientLightColor.value = lights.state.ambient; uniforms.lightProbe.value = lights.state.probe; uniforms.directionalLights.value = lights.state.directional; uniforms.spotLights.value = lights.state.spot; uniforms.rectAreaLights.value = lights.state.rectArea; uniforms.pointLights.value = lights.state.point; uniforms.hemisphereLights.value = lights.state.hemi; uniforms.directionalShadowMap.value = lights.state.directionalShadowMap; uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix; uniforms.spotShadowMap.value = lights.state.spotShadowMap; uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix; uniforms.pointShadowMap.value = lights.state.pointShadowMap; uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix; // TODO (abelnation): add area lights shadow info to uniforms } var progUniforms = materialProperties.program.getUniforms(), uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, uniforms ); materialProperties.uniformsList = uniformsList; } function setProgram( camera, scene, material, object ) { textures.resetTextureUnits(); var fog = scene.fog; var environment = material.isMeshStandardMaterial ? scene.environment : null; var materialProperties = properties.get( material ); var lights = currentRenderState.state.lights; if ( _clippingEnabled ) { if ( _localClippingEnabled || camera !== _currentCamera ) { var useCache = camera === _currentCamera && material.id === _currentMaterialId; // we might want to call this function with some ClippingGroup // object instead of the material, once it becomes feasible // (#8465, #8379) _clipping.setState( material.clippingPlanes, material.clipIntersection, material.clipShadows, camera, materialProperties, useCache ); } } if ( material.version === materialProperties.__version ) { if ( materialProperties.program === undefined ) { initMaterial( material, scene, object ); } else if ( material.fog && materialProperties.fog !== fog ) { initMaterial( material, scene, object ); } else if ( materialProperties.environment !== environment ) { initMaterial( material, scene, object ); } else if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) { initMaterial( material, scene, object ); } else if ( materialProperties.numClippingPlanes !== undefined && ( materialProperties.numClippingPlanes !== _clipping.numPlanes || materialProperties.numIntersection !== _clipping.numIntersection ) ) { initMaterial( material, scene, object ); } else if ( materialProperties.outputEncoding !== _this.outputEncoding ) { initMaterial( material, scene, object ); } } else { initMaterial( material, scene, object ); materialProperties.__version = material.version; } var refreshProgram = false; var refreshMaterial = false; var refreshLights = false; var program = materialProperties.program, p_uniforms = program.getUniforms(), m_uniforms = materialProperties.uniforms; if ( state.useProgram( program.program ) ) { refreshProgram = true; refreshMaterial = true; refreshLights = true; } if ( material.id !== _currentMaterialId ) { _currentMaterialId = material.id; refreshMaterial = true; } if ( refreshProgram || _currentCamera !== camera ) { if ( program.numMultiviewViews > 0 ) { multiview.updateCameraProjectionMatricesUniform( camera, p_uniforms ); } else { p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix ); } if ( capabilities.logarithmicDepthBuffer ) { p_uniforms.setValue( _gl, 'logDepthBufFC', 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) ); } if ( _currentCamera !== camera ) { _currentCamera = camera; // lighting uniforms depend on the camera so enforce an update // now, in case this material supports lights - or later, when // the next material that does gets activated: refreshMaterial = true; // set to true on material change refreshLights = true; // remains set until update done } // load material specific uniforms // (shader material also gets them for the sake of genericity) if ( material.isShaderMaterial || material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshStandardMaterial || material.envMap ) { var uCamPos = p_uniforms.map.cameraPosition; if ( uCamPos !== undefined ) { uCamPos.setValue( _gl, _vector3.setFromMatrixPosition( camera.matrixWorld ) ); } } if ( material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial ) { p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true ); } if ( material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial || material.skinning ) { if ( program.numMultiviewViews > 0 ) { multiview.updateCameraViewMatricesUniform( camera, p_uniforms ); } else { p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse ); } } } // skinning uniforms must be set even if material didn't change // auto-setting of texture unit for bone texture must go before other textures // not sure why, but otherwise weird things happen if ( material.skinning ) { p_uniforms.setOptional( _gl, object, 'bindMatrix' ); p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' ); var skeleton = object.skeleton; if ( skeleton ) { var bones = skeleton.bones; if ( capabilities.floatVertexTextures ) { if ( skeleton.boneTexture === undefined ) { // layout (1 matrix = 4 pixels) // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4) // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8) // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16) // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32) // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64) var size = Math.sqrt( bones.length * 4 ); // 4 pixels needed for 1 matrix size = MathUtils.ceilPowerOfTwo( size ); size = Math.max( size, 4 ); var boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel boneMatrices.set( skeleton.boneMatrices ); // copy current values var boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType ); skeleton.boneMatrices = boneMatrices; skeleton.boneTexture = boneTexture; skeleton.boneTextureSize = size; } p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures ); p_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize ); } else { p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' ); } } } if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) { materialProperties.receiveShadow = object.receiveShadow; p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow ); } if ( refreshMaterial ) { p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure ); p_uniforms.setValue( _gl, 'toneMappingWhitePoint', _this.toneMappingWhitePoint ); if ( materialProperties.needsLights ) { // the current material requires lighting info // note: all lighting uniforms are always set correctly // they simply reference the renderer's state for their // values // // use the current material's .needsUpdate flags to set // the GL state when required markUniformsLightsNeedsUpdate( m_uniforms, refreshLights ); } // refresh uniforms common to several materials if ( fog && material.fog ) { refreshUniformsFog( m_uniforms, fog ); } if ( material.isMeshBasicMaterial ) { refreshUniformsCommon( m_uniforms, material ); } else if ( material.isMeshLambertMaterial ) { refreshUniformsCommon( m_uniforms, material ); refreshUniformsLambert( m_uniforms, material ); } else if ( material.isMeshToonMaterial ) { refreshUniformsCommon( m_uniforms, material ); refreshUniformsToon( m_uniforms, material ); } else if ( material.isMeshPhongMaterial ) { refreshUniformsCommon( m_uniforms, material ); refreshUniformsPhong( m_uniforms, material ); } else if ( material.isMeshStandardMaterial ) { refreshUniformsCommon( m_uniforms, material, environment ); if ( material.isMeshPhysicalMaterial ) { refreshUniformsPhysical( m_uniforms, material, environment ); } else { refreshUniformsStandard( m_uniforms, material, environment ); } } else if ( material.isMeshMatcapMaterial ) { refreshUniformsCommon( m_uniforms, material ); refreshUniformsMatcap( m_uniforms, material ); } else if ( material.isMeshDepthMaterial ) { refreshUniformsCommon( m_uniforms, material ); refreshUniformsDepth( m_uniforms, material ); } else if ( material.isMeshDistanceMaterial ) { refreshUniformsCommon( m_uniforms, material ); refreshUniformsDistance( m_uniforms, material ); } else if ( material.isMeshNormalMaterial ) { refreshUniformsCommon( m_uniforms, material ); refreshUniformsNormal( m_uniforms, material ); } else if ( material.isLineBasicMaterial ) { refreshUniformsLine( m_uniforms, material ); if ( material.isLineDashedMaterial ) { refreshUniformsDash( m_uniforms, material ); } } else if ( material.isPointsMaterial ) { refreshUniformsPoints( m_uniforms, material ); } else if ( material.isSpriteMaterial ) { refreshUniformsSprites( m_uniforms, material ); } else if ( material.isShadowMaterial ) { m_uniforms.color.value.copy( material.color ); m_uniforms.opacity.value = material.opacity; } // RectAreaLight Texture // TODO (mrdoob): Find a nicer implementation if ( m_uniforms.ltc_1 !== undefined ) { m_uniforms.ltc_1.value = UniformsLib.LTC_1; } if ( m_uniforms.ltc_2 !== undefined ) { m_uniforms.ltc_2.value = UniformsLib.LTC_2; } WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures ); if ( material.isShaderMaterial ) { material.uniformsNeedUpdate = false; // #15581 } } if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) { WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures ); material.uniformsNeedUpdate = false; } if ( material.isSpriteMaterial ) { p_uniforms.setValue( _gl, 'center', object.center ); } // common matrices if ( program.numMultiviewViews > 0 ) { multiview.updateObjectMatricesUniforms( object, camera, p_uniforms ); } else { p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix ); p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix ); } p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld ); return program; } // Uniforms (refresh uniforms objects) function refreshUniformsCommon( uniforms, material, environment ) { uniforms.opacity.value = material.opacity; if ( material.color ) { uniforms.diffuse.value.copy( material.color ); } if ( material.emissive ) { uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity ); } if ( material.map ) { uniforms.map.value = material.map; } if ( material.alphaMap ) { uniforms.alphaMap.value = material.alphaMap; } if ( material.specularMap ) { uniforms.specularMap.value = material.specularMap; } var envMap = material.envMap || environment; if ( envMap ) { uniforms.envMap.value = envMap; uniforms.flipEnvMap.value = envMap.isCubeTexture ? - 1 : 1; uniforms.reflectivity.value = material.reflectivity; uniforms.refractionRatio.value = material.refractionRatio; uniforms.maxMipLevel.value = properties.get( envMap ).__maxMipLevel; } if ( material.lightMap ) { uniforms.lightMap.value = material.lightMap; uniforms.lightMapIntensity.value = material.lightMapIntensity; } if ( material.aoMap ) { uniforms.aoMap.value = material.aoMap; uniforms.aoMapIntensity.value = material.aoMapIntensity; } // uv repeat and offset setting priorities // 1. color map // 2. specular map // 3. normal map // 4. bump map // 5. alpha map // 6. emissive map var uvScaleMap; if ( material.map ) { uvScaleMap = material.map; } else if ( material.specularMap ) { uvScaleMap = material.specularMap; } else if ( material.displacementMap ) { uvScaleMap = material.displacementMap; } else if ( material.normalMap ) { uvScaleMap = material.normalMap; } else if ( material.bumpMap ) { uvScaleMap = material.bumpMap; } else if ( material.roughnessMap ) { uvScaleMap = material.roughnessMap; } else if ( material.metalnessMap ) { uvScaleMap = material.metalnessMap; } else if ( material.alphaMap ) { uvScaleMap = material.alphaMap; } else if ( material.emissiveMap ) { uvScaleMap = material.emissiveMap; } if ( uvScaleMap !== undefined ) { // backwards compatibility if ( uvScaleMap.isWebGLRenderTarget ) { uvScaleMap = uvScaleMap.texture; } if ( uvScaleMap.matrixAutoUpdate === true ) { uvScaleMap.updateMatrix(); } uniforms.uvTransform.value.copy( uvScaleMap.matrix ); } // uv repeat and offset setting priorities for uv2 // 1. ao map // 2. light map var uv2ScaleMap; if ( material.aoMap ) { uv2ScaleMap = material.aoMap; } else if ( material.lightMap ) { uv2ScaleMap = material.lightMap; } if ( uv2ScaleMap !== undefined ) { // backwards compatibility if ( uv2ScaleMap.isWebGLRenderTarget ) { uv2ScaleMap = uv2ScaleMap.texture; } if ( uv2ScaleMap.matrixAutoUpdate === true ) { uv2ScaleMap.updateMatrix(); } uniforms.uv2Transform.value.copy( uv2ScaleMap.matrix ); } } function refreshUniformsLine( uniforms, material ) { uniforms.diffuse.value.copy( material.color ); uniforms.opacity.value = material.opacity; } function refreshUniformsDash( uniforms, material ) { uniforms.dashSize.value = material.dashSize; uniforms.totalSize.value = material.dashSize + material.gapSize; uniforms.scale.value = material.scale; } function refreshUniformsPoints( uniforms, material ) { uniforms.diffuse.value.copy( material.color ); uniforms.opacity.value = material.opacity; uniforms.size.value = material.size * _pixelRatio; uniforms.scale.value = _height * 0.5; if ( material.map ) { uniforms.map.value = material.map; } if ( material.alphaMap ) { uniforms.alphaMap.value = material.alphaMap; } // uv repeat and offset setting priorities // 1. color map // 2. alpha map var uvScaleMap; if ( material.map ) { uvScaleMap = material.map; } else if ( material.alphaMap ) { uvScaleMap = material.alphaMap; } if ( uvScaleMap !== undefined ) { if ( uvScaleMap.matrixAutoUpdate === true ) { uvScaleMap.updateMatrix(); } uniforms.uvTransform.value.copy( uvScaleMap.matrix ); } } function refreshUniformsSprites( uniforms, material ) { uniforms.diffuse.value.copy( material.color ); uniforms.opacity.value = material.opacity; uniforms.rotation.value = material.rotation; if ( material.map ) { uniforms.map.value = material.map; } if ( material.alphaMap ) { uniforms.alphaMap.value = material.alphaMap; } // uv repeat and offset setting priorities // 1. color map // 2. alpha map var uvScaleMap; if ( material.map ) { uvScaleMap = material.map; } else if ( material.alphaMap ) { uvScaleMap = material.alphaMap; } if ( uvScaleMap !== undefined ) { if ( uvScaleMap.matrixAutoUpdate === true ) { uvScaleMap.updateMatrix(); } uniforms.uvTransform.value.copy( uvScaleMap.matrix ); } } function refreshUniformsFog( uniforms, fog ) { uniforms.fogColor.value.copy( fog.color ); if ( fog.isFog ) { uniforms.fogNear.value = fog.near; uniforms.fogFar.value = fog.far; } else if ( fog.isFogExp2 ) { uniforms.fogDensity.value = fog.density; } } function refreshUniformsLambert( uniforms, material ) { if ( material.emissiveMap ) { uniforms.emissiveMap.value = material.emissiveMap; } } function refreshUniformsPhong( uniforms, material ) { uniforms.specular.value.copy( material.specular ); uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 ) if ( material.emissiveMap ) { uniforms.emissiveMap.value = material.emissiveMap; } if ( material.bumpMap ) { uniforms.bumpMap.value = material.bumpMap; uniforms.bumpScale.value = material.bumpScale; if ( material.side === BackSide ) { uniforms.bumpScale.value *= - 1; } } if ( material.normalMap ) { uniforms.normalMap.value = material.normalMap; uniforms.normalScale.value.copy( material.normalScale ); if ( material.side === BackSide ) { uniforms.normalScale.value.negate(); } } if ( material.displacementMap ) { uniforms.displacementMap.value = material.displacementMap; uniforms.displacementScale.value = material.displacementScale; uniforms.displacementBias.value = material.displacementBias; } } function refreshUniformsToon( uniforms, material ) { uniforms.specular.value.copy( material.specular ); uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 ) if ( material.gradientMap ) { uniforms.gradientMap.value = material.gradientMap; } if ( material.emissiveMap ) { uniforms.emissiveMap.value = material.emissiveMap; } if ( material.bumpMap ) { uniforms.bumpMap.value = material.bumpMap; uniforms.bumpScale.value = material.bumpScale; if ( material.side === BackSide ) { uniforms.bumpScale.value *= - 1; } } if ( material.normalMap ) { uniforms.normalMap.value = material.normalMap; uniforms.normalScale.value.copy( material.normalScale ); if ( material.side === BackSide ) { uniforms.normalScale.value.negate(); } } if ( material.displacementMap ) { uniforms.displacementMap.value = material.displacementMap; uniforms.displacementScale.value = material.displacementScale; uniforms.displacementBias.value = material.displacementBias; } } function refreshUniformsStandard( uniforms, material, environment ) { uniforms.roughness.value = material.roughness; uniforms.metalness.value = material.metalness; if ( material.roughnessMap ) { uniforms.roughnessMap.value = material.roughnessMap; } if ( material.metalnessMap ) { uniforms.metalnessMap.value = material.metalnessMap; } if ( material.emissiveMap ) { uniforms.emissiveMap.value = material.emissiveMap; } if ( material.bumpMap ) { uniforms.bumpMap.value = material.bumpMap; uniforms.bumpScale.value = material.bumpScale; if ( material.side === BackSide ) { uniforms.bumpScale.value *= - 1; } } if ( material.normalMap ) { uniforms.normalMap.value = material.normalMap; uniforms.normalScale.value.copy( material.normalScale ); if ( material.side === BackSide ) { uniforms.normalScale.value.negate(); } } if ( material.displacementMap ) { uniforms.displacementMap.value = material.displacementMap; uniforms.displacementScale.value = material.displacementScale; uniforms.displacementBias.value = material.displacementBias; } if ( material.envMap || environment ) { //uniforms.envMap.value = material.envMap; // part of uniforms common uniforms.envMapIntensity.value = material.envMapIntensity; } } function refreshUniformsPhysical( uniforms, material, environment ) { refreshUniformsStandard( uniforms, material, environment ); uniforms.reflectivity.value = material.reflectivity; // also part of uniforms common uniforms.clearcoat.value = material.clearcoat; uniforms.clearcoatRoughness.value = material.clearcoatRoughness; if ( material.sheen ) { uniforms.sheen.value.copy( material.sheen ); } if ( material.clearcoatNormalMap ) { uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale ); uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap; if ( material.side === BackSide ) { uniforms.clearcoatNormalScale.value.negate(); } } uniforms.transparency.value = material.transparency; } function refreshUniformsMatcap( uniforms, material ) { if ( material.matcap ) { uniforms.matcap.value = material.matcap; } if ( material.bumpMap ) { uniforms.bumpMap.value = material.bumpMap; uniforms.bumpScale.value = material.bumpScale; if ( material.side === BackSide ) { uniforms.bumpScale.value *= - 1; } } if ( material.normalMap ) { uniforms.normalMap.value = material.normalMap; uniforms.normalScale.value.copy( material.normalScale ); if ( material.side === BackSide ) { uniforms.normalScale.value.negate(); } } if ( material.displacementMap ) { uniforms.displacementMap.value = material.displacementMap; uniforms.displacementScale.value = material.displacementScale; uniforms.displacementBias.value = material.displacementBias; } } function refreshUniformsDepth( uniforms, material ) { if ( material.displacementMap ) { uniforms.displacementMap.value = material.displacementMap; uniforms.displacementScale.value = material.displacementScale; uniforms.displacementBias.value = material.displacementBias; } } function refreshUniformsDistance( uniforms, material ) { if ( material.displacementMap ) { uniforms.displacementMap.value = material.displacementMap; uniforms.displacementScale.value = material.displacementScale; uniforms.displacementBias.value = material.displacementBias; } uniforms.referencePosition.value.copy( material.referencePosition ); uniforms.nearDistance.value = material.nearDistance; uniforms.farDistance.value = material.farDistance; } function refreshUniformsNormal( uniforms, material ) { if ( material.bumpMap ) { uniforms.bumpMap.value = material.bumpMap; uniforms.bumpScale.value = material.bumpScale; if ( material.side === BackSide ) { uniforms.bumpScale.value *= - 1; } } if ( material.normalMap ) { uniforms.normalMap.value = material.normalMap; uniforms.normalScale.value.copy( material.normalScale ); if ( material.side === BackSide ) { uniforms.normalScale.value.negate(); } } if ( material.displacementMap ) { uniforms.displacementMap.value = material.displacementMap; uniforms.displacementScale.value = material.displacementScale; uniforms.displacementBias.value = material.displacementBias; } } // If uniforms are marked as clean, they don't need to be loaded to the GPU. function markUniformsLightsNeedsUpdate( uniforms, value ) { uniforms.ambientLightColor.needsUpdate = value; uniforms.lightProbe.needsUpdate = value; uniforms.directionalLights.needsUpdate = value; uniforms.pointLights.needsUpdate = value; uniforms.spotLights.needsUpdate = value; uniforms.rectAreaLights.needsUpdate = value; uniforms.hemisphereLights.needsUpdate = value; } function materialNeedsLights( material ) { return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial || material.isShadowMaterial || ( material.isShaderMaterial && material.lights === true ); } // this.setFramebuffer = function ( value ) { if ( _framebuffer !== value && _currentRenderTarget === null ) { _gl.bindFramebuffer( 36160, value ); } _framebuffer = value; }; this.getActiveCubeFace = function () { return _currentActiveCubeFace; }; this.getActiveMipmapLevel = function () { return _currentActiveMipmapLevel; }; this.getRenderTarget = function () { return _currentRenderTarget; }; this.setRenderTarget = function ( renderTarget, activeCubeFace, activeMipmapLevel ) { _currentRenderTarget = renderTarget; _currentActiveCubeFace = activeCubeFace; _currentActiveMipmapLevel = activeMipmapLevel; if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) { textures.setupRenderTarget( renderTarget ); } var framebuffer = _framebuffer; var isCube = false; if ( renderTarget ) { var __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer; if ( renderTarget.isWebGLCubeRenderTarget ) { framebuffer = __webglFramebuffer[ activeCubeFace || 0 ]; isCube = true; } else if ( renderTarget.isWebGLMultisampleRenderTarget ) { framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer; } else { framebuffer = __webglFramebuffer; } _currentViewport.copy( renderTarget.viewport ); _currentScissor.copy( renderTarget.scissor ); _currentScissorTest = renderTarget.scissorTest; } else { _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor(); _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor(); _currentScissorTest = _scissorTest; } if ( _currentFramebuffer !== framebuffer ) { _gl.bindFramebuffer( 36160, framebuffer ); _currentFramebuffer = framebuffer; } state.viewport( _currentViewport ); state.scissor( _currentScissor ); state.setScissorTest( _currentScissorTest ); if ( isCube ) { var textureProperties = properties.get( renderTarget.texture ); _gl.framebufferTexture2D( 36160, 36064, 34069 + ( activeCubeFace || 0 ), textureProperties.__webglTexture, activeMipmapLevel || 0 ); } }; this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) { if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) { console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' ); return; } var framebuffer = properties.get( renderTarget ).__webglFramebuffer; if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) { framebuffer = framebuffer[ activeCubeFaceIndex ]; } if ( framebuffer ) { var restore = false; if ( framebuffer !== _currentFramebuffer ) { _gl.bindFramebuffer( 36160, framebuffer ); restore = true; } try { var texture = renderTarget.texture; var textureFormat = texture.format; var textureType = texture.type; if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== _gl.getParameter( 35739 ) ) { console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' ); return; } if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== _gl.getParameter( 35738 ) && // IE11, Edge and Chrome Mac < 52 (#9513) ! ( textureType === FloatType && ( capabilities.isWebGL2 || extensions.get( 'OES_texture_float' ) || extensions.get( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox ! ( textureType === HalfFloatType && ( capabilities.isWebGL2 ? extensions.get( 'EXT_color_buffer_float' ) : extensions.get( 'EXT_color_buffer_half_float' ) ) ) ) { console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' ); return; } if ( _gl.checkFramebufferStatus( 36160 ) === 36053 ) { // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604) if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) { _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer ); } } else { console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' ); } } finally { if ( restore ) { _gl.bindFramebuffer( 36160, _currentFramebuffer ); } } } }; this.copyFramebufferToTexture = function ( position, texture, level ) { if ( level === undefined ) { level = 0; } var levelScale = Math.pow( 2, - level ); var width = Math.floor( texture.image.width * levelScale ); var height = Math.floor( texture.image.height * levelScale ); var glFormat = utils.convert( texture.format ); textures.setTexture2D( texture, 0 ); _gl.copyTexImage2D( 3553, level, glFormat, position.x, position.y, width, height, 0 ); state.unbindTexture(); }; this.copyTextureToTexture = function ( position, srcTexture, dstTexture, level ) { var width = srcTexture.image.width; var height = srcTexture.image.height; var glFormat = utils.convert( dstTexture.format ); var glType = utils.convert( dstTexture.type ); textures.setTexture2D( dstTexture, 0 ); if ( srcTexture.isDataTexture ) { _gl.texSubImage2D( 3553, level || 0, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data ); } else { _gl.texSubImage2D( 3553, level || 0, position.x, position.y, glFormat, glType, srcTexture.image ); } state.unbindTexture(); }; this.initTexture = function ( texture ) { textures.setTexture2D( texture, 0 ); state.unbindTexture(); }; if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) { __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) ); // eslint-disable-line no-undef } } /** * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ */ function FogExp2( color, density ) { this.name = ''; this.color = new Color( color ); this.density = ( density !== undefined ) ? density : 0.00025; } Object.assign( FogExp2.prototype, { isFogExp2: true, clone: function () { return new FogExp2( this.color, this.density ); }, toJSON: function ( /* meta */ ) { return { type: 'FogExp2', color: this.color.getHex(), density: this.density }; } } ); /** * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ */ function Fog( color, near, far ) { this.name = ''; this.color = new Color( color ); this.near = ( near !== undefined ) ? near : 1; this.far = ( far !== undefined ) ? far : 1000; } Object.assign( Fog.prototype, { isFog: true, clone: function () { return new Fog( this.color, this.near, this.far ); }, toJSON: function ( /* meta */ ) { return { type: 'Fog', color: this.color.getHex(), near: this.near, far: this.far }; } } ); /** * @author benaadams / https://twitter.com/ben_a_adams */ function InterleavedBuffer( array, stride ) { this.array = array; this.stride = stride; this.count = array !== undefined ? array.length / stride : 0; this.usage = StaticDrawUsage; this.updateRange = { offset: 0, count: - 1 }; this.version = 0; } Object.defineProperty( InterleavedBuffer.prototype, 'needsUpdate', { set: function ( value ) { if ( value === true ) { this.version ++; } } } ); Object.assign( InterleavedBuffer.prototype, { isInterleavedBuffer: true, onUploadCallback: function () {}, setUsage: function ( value ) { this.usage = value; return this; }, copy: function ( source ) { this.array = new source.array.constructor( source.array ); this.count = source.count; this.stride = source.stride; this.usage = source.usage; return this; }, copyAt: function ( index1, attribute, index2 ) { index1 *= this.stride; index2 *= attribute.stride; for ( var i = 0, l = this.stride; i < l; i ++ ) { this.array[ index1 + i ] = attribute.array[ index2 + i ]; } return this; }, set: function ( value, offset ) { if ( offset === undefined ) { offset = 0; } this.array.set( value, offset ); return this; }, clone: function () { return new this.constructor().copy( this ); }, onUpload: function ( callback ) { this.onUploadCallback = callback; return this; } } ); /** * @author benaadams / https://twitter.com/ben_a_adams */ var _vector$6 = new Vector3(); function InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, normalized ) { this.data = interleavedBuffer; this.itemSize = itemSize; this.offset = offset; this.normalized = normalized === true; } Object.defineProperties( InterleavedBufferAttribute.prototype, { count: { get: function () { return this.data.count; } }, array: { get: function () { return this.data.array; } } } ); Object.assign( InterleavedBufferAttribute.prototype, { isInterleavedBufferAttribute: true, applyMatrix4: function ( m ) { for ( var i = 0, l = this.data.count; i < l; i ++ ) { _vector$6.x = this.getX( i ); _vector$6.y = this.getY( i ); _vector$6.z = this.getZ( i ); _vector$6.applyMatrix4( m ); this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z ); } return this; }, setX: function ( index, x ) { this.data.array[ index * this.data.stride + this.offset ] = x; return this; }, setY: function ( index, y ) { this.data.array[ index * this.data.stride + this.offset + 1 ] = y; return this; }, setZ: function ( index, z ) { this.data.array[ index * this.data.stride + this.offset + 2 ] = z; return this; }, setW: function ( index, w ) { this.data.array[ index * this.data.stride + this.offset + 3 ] = w; return this; }, getX: function ( index ) { return this.data.array[ index * this.data.stride + this.offset ]; }, getY: function ( index ) { return this.data.array[ index * this.data.stride + this.offset + 1 ]; }, getZ: function ( index ) { return this.data.array[ index * this.data.stride + this.offset + 2 ]; }, getW: function ( index ) { return this.data.array[ index * this.data.stride + this.offset + 3 ]; }, setXY: function ( index, x, y ) { index = index * this.data.stride + this.offset; this.data.array[ index + 0 ] = x; this.data.array[ index + 1 ] = y; return this; }, setXYZ: function ( index, x, y, z ) { index = index * this.data.stride + this.offset; this.data.array[ index + 0 ] = x; this.data.array[ index + 1 ] = y; this.data.array[ index + 2 ] = z; return this; }, setXYZW: function ( index, x, y, z, w ) { index = index * this.data.stride + this.offset; this.data.array[ index + 0 ] = x; this.data.array[ index + 1 ] = y; this.data.array[ index + 2 ] = z; this.data.array[ index + 3 ] = w; return this; } } ); /** * @author alteredq / http://alteredqualia.com/ * * parameters = { * color: , * map: new THREE.Texture( ), * alphaMap: new THREE.Texture( ), * rotation: , * sizeAttenuation: * } */ function SpriteMaterial( parameters ) { Material.call( this ); this.type = 'SpriteMaterial'; this.color = new Color( 0xffffff ); this.map = null; this.alphaMap = null; this.rotation = 0; this.sizeAttenuation = true; this.transparent = true; this.setValues( parameters ); } SpriteMaterial.prototype = Object.create( Material.prototype ); SpriteMaterial.prototype.constructor = SpriteMaterial; SpriteMaterial.prototype.isSpriteMaterial = true; SpriteMaterial.prototype.copy = function ( source ) { Material.prototype.copy.call( this, source ); this.color.copy( source.color ); this.map = source.map; this.alphaMap = source.alphaMap; this.rotation = source.rotation; this.sizeAttenuation = source.sizeAttenuation; return this; }; /** * @author mikael emtinger / http://gomo.se/ * @author alteredq / http://alteredqualia.com/ */ var _geometry; var _intersectPoint = new Vector3(); var _worldScale = new Vector3(); var _mvPosition = new Vector3(); var _alignedPosition = new Vector2(); var _rotatedPosition = new Vector2(); var _viewWorldMatrix = new Matrix4(); var _vA$1 = new Vector3(); var _vB$1 = new Vector3(); var _vC$1 = new Vector3(); var _uvA$1 = new Vector2(); var _uvB$1 = new Vector2(); var _uvC$1 = new Vector2(); function Sprite( material ) { Object3D.call( this ); this.type = 'Sprite'; if ( _geometry === undefined ) { _geometry = new BufferGeometry(); var float32Array = new Float32Array( [ - 0.5, - 0.5, 0, 0, 0, 0.5, - 0.5, 0, 1, 0, 0.5, 0.5, 0, 1, 1, - 0.5, 0.5, 0, 0, 1 ] ); var interleavedBuffer = new InterleavedBuffer( float32Array, 5 ); _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] ); _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) ); _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) ); } this.geometry = _geometry; this.material = ( material !== undefined ) ? material : new SpriteMaterial(); this.center = new Vector2( 0.5, 0.5 ); } Sprite.prototype = Object.assign( Object.create( Object3D.prototype ), { constructor: Sprite, isSprite: true, raycast: function ( raycaster, intersects ) { if ( raycaster.camera === null ) { console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' ); } _worldScale.setFromMatrixScale( this.matrixWorld ); _viewWorldMatrix.copy( raycaster.camera.matrixWorld ); this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld ); _mvPosition.setFromMatrixPosition( this.modelViewMatrix ); if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) { _worldScale.multiplyScalar( - _mvPosition.z ); } var rotation = this.material.rotation; var sin, cos; if ( rotation !== 0 ) { cos = Math.cos( rotation ); sin = Math.sin( rotation ); } var center = this.center; transformVertex( _vA$1.set( - 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos ); transformVertex( _vB$1.set( 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos ); transformVertex( _vC$1.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos ); _uvA$1.set( 0, 0 ); _uvB$1.set( 1, 0 ); _uvC$1.set( 1, 1 ); // check first triangle var intersect = raycaster.ray.intersectTriangle( _vA$1, _vB$1, _vC$1, false, _intersectPoint ); if ( intersect === null ) { // check second triangle transformVertex( _vB$1.set( - 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos ); _uvB$1.set( 0, 1 ); intersect = raycaster.ray.intersectTriangle( _vA$1, _vC$1, _vB$1, false, _intersectPoint ); if ( intersect === null ) { return; } } var distance = raycaster.ray.origin.distanceTo( _intersectPoint ); if ( distance < raycaster.near || distance > raycaster.far ) { return; } intersects.push( { distance: distance, point: _intersectPoint.clone(), uv: Triangle.getUV( _intersectPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() ), face: null, object: this } ); }, clone: function () { return new this.constructor( this.material ).copy( this ); }, copy: function ( source ) { Object3D.prototype.copy.call( this, source ); if ( source.center !== undefined ) { this.center.copy( source.center ); } return this; } } ); function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) { // compute position in camera space _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale ); // to check if rotation is not zero if ( sin !== undefined ) { _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y ); _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y ); } else { _rotatedPosition.copy( _alignedPosition ); } vertexPosition.copy( mvPosition ); vertexPosition.x += _rotatedPosition.x; vertexPosition.y += _rotatedPosition.y; // transform to world space vertexPosition.applyMatrix4( _viewWorldMatrix ); } /** * @author mikael emtinger / http://gomo.se/ * @author alteredq / http://alteredqualia.com/ * @author mrdoob / http://mrdoob.com/ */ var _v1$4 = new Vector3(); var _v2$2 = new Vector3(); function LOD() { Object3D.call( this ); this.type = 'LOD'; Object.defineProperties( this, { levels: { enumerable: true, value: [] } } ); this.autoUpdate = true; } LOD.prototype = Object.assign( Object.create( Object3D.prototype ), { constructor: LOD, isLOD: true, copy: function ( source ) { Object3D.prototype.copy.call( this, source, false ); var levels = source.levels; for ( var i = 0, l = levels.length; i < l; i ++ ) { var level = levels[ i ]; this.addLevel( level.object.clone(), level.distance ); } this.autoUpdate = source.autoUpdate; return this; }, addLevel: function ( object, distance ) { if ( distance === undefined ) { distance = 0; } distance = Math.abs( distance ); var levels = this.levels; for ( var l = 0; l < levels.length; l ++ ) { if ( distance < levels[ l ].distance ) { break; } } levels.splice( l, 0, { distance: distance, object: object } ); this.add( object ); return this; }, getObjectForDistance: function ( distance ) { var levels = this.levels; if ( levels.length > 0 ) { for ( var i = 1, l = levels.length; i < l; i ++ ) { if ( distance < levels[ i ].distance ) { break; } } return levels[ i - 1 ].object; } return null; }, raycast: function ( raycaster, intersects ) { var levels = this.levels; if ( levels.length > 0 ) { _v1$4.setFromMatrixPosition( this.matrixWorld ); var distance = raycaster.ray.origin.distanceTo( _v1$4 ); this.getObjectForDistance( distance ).raycast( raycaster, intersects ); } }, update: function ( camera ) { var levels = this.levels; if ( levels.length > 1 ) { _v1$4.setFromMatrixPosition( camera.matrixWorld ); _v2$2.setFromMatrixPosition( this.matrixWorld ); var distance = _v1$4.distanceTo( _v2$2 ); levels[ 0 ].object.visible = true; for ( var i = 1, l = levels.length; i < l; i ++ ) { if ( distance >= levels[ i ].distance ) { levels[ i - 1 ].object.visible = false; levels[ i ].object.visible = true; } else { break; } } for ( ; i < l; i ++ ) { levels[ i ].object.visible = false; } } }, toJSON: function ( meta ) { var data = Object3D.prototype.toJSON.call( this, meta ); if ( this.autoUpdate === false ) { data.object.autoUpdate = false; } data.object.levels = []; var levels = this.levels; for ( var i = 0, l = levels.length; i < l; i ++ ) { var level = levels[ i ]; data.object.levels.push( { object: level.object.uuid, distance: level.distance } ); } return data; } } ); /** * @author mikael emtinger / http://gomo.se/ * @author alteredq / http://alteredqualia.com/ * @author ikerr / http://verold.com */ function SkinnedMesh( geometry, material ) { if ( geometry && geometry.isGeometry ) { console.error( 'THREE.SkinnedMesh no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' ); } Mesh.call( this, geometry, material ); this.type = 'SkinnedMesh'; this.bindMode = 'attached'; this.bindMatrix = new Matrix4(); this.bindMatrixInverse = new Matrix4(); } SkinnedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), { constructor: SkinnedMesh, isSkinnedMesh: true, bind: function ( skeleton, bindMatrix ) { this.skeleton = skeleton; if ( bindMatrix === undefined ) { this.updateMatrixWorld( true ); this.skeleton.calculateInverses(); bindMatrix = this.matrixWorld; } this.bindMatrix.copy( bindMatrix ); this.bindMatrixInverse.getInverse( bindMatrix ); }, pose: function () { this.skeleton.pose(); }, normalizeSkinWeights: function () { var vector = new Vector4(); var skinWeight = this.geometry.attributes.skinWeight; for ( var i = 0, l = skinWeight.count; i < l; i ++ ) { vector.x = skinWeight.getX( i ); vector.y = skinWeight.getY( i ); vector.z = skinWeight.getZ( i ); vector.w = skinWeight.getW( i ); var scale = 1.0 / vector.manhattanLength(); if ( scale !== Infinity ) { vector.multiplyScalar( scale ); } else { vector.set( 1, 0, 0, 0 ); // do something reasonable } skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w ); } }, updateMatrixWorld: function ( force ) { Mesh.prototype.updateMatrixWorld.call( this, force ); if ( this.bindMode === 'attached' ) { this.bindMatrixInverse.getInverse( this.matrixWorld ); } else if ( this.bindMode === 'detached' ) { this.bindMatrixInverse.getInverse( this.bindMatrix ); } else { console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode ); } }, clone: function () { return new this.constructor( this.geometry, this.material ).copy( this ); } } ); /** * @author mikael emtinger / http://gomo.se/ * @author alteredq / http://alteredqualia.com/ * @author michael guerrero / http://realitymeltdown.com * @author ikerr / http://verold.com */ var _offsetMatrix = new Matrix4(); var _identityMatrix = new Matrix4(); function Skeleton( bones, boneInverses ) { // copy the bone array bones = bones || []; this.bones = bones.slice( 0 ); this.boneMatrices = new Float32Array( this.bones.length * 16 ); this.frame = - 1; // use the supplied bone inverses or calculate the inverses if ( boneInverses === undefined ) { this.calculateInverses(); } else { if ( this.bones.length === boneInverses.length ) { this.boneInverses = boneInverses.slice( 0 ); } else { console.warn( 'THREE.Skeleton boneInverses is the wrong length.' ); this.boneInverses = []; for ( var i = 0, il = this.bones.length; i < il; i ++ ) { this.boneInverses.push( new Matrix4() ); } } } } Object.assign( Skeleton.prototype, { calculateInverses: function () { this.boneInverses = []; for ( var i = 0, il = this.bones.length; i < il; i ++ ) { var inverse = new Matrix4(); if ( this.bones[ i ] ) { inverse.getInverse( this.bones[ i ].matrixWorld ); } this.boneInverses.push( inverse ); } }, pose: function () { var bone, i, il; // recover the bind-time world matrices for ( i = 0, il = this.bones.length; i < il; i ++ ) { bone = this.bones[ i ]; if ( bone ) { bone.matrixWorld.getInverse( this.boneInverses[ i ] ); } } // compute the local matrices, positions, rotations and scales for ( i = 0, il = this.bones.length; i < il; i ++ ) { bone = this.bones[ i ]; if ( bone ) { if ( bone.parent && bone.parent.isBone ) { bone.matrix.getInverse( bone.parent.matrixWorld ); bone.matrix.multiply( bone.matrixWorld ); } else { bone.matrix.copy( bone.matrixWorld ); } bone.matrix.decompose( bone.position, bone.quaternion, bone.scale ); } } }, update: function () { var bones = this.bones; var boneInverses = this.boneInverses; var boneMatrices = this.boneMatrices; var boneTexture = this.boneTexture; // flatten bone matrices to array for ( var i = 0, il = bones.length; i < il; i ++ ) { // compute the offset between the current and the original transform var matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix; _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] ); _offsetMatrix.toArray( boneMatrices, i * 16 ); } if ( boneTexture !== undefined ) { boneTexture.needsUpdate = true; } }, clone: function () { return new Skeleton( this.bones, this.boneInverses ); }, getBoneByName: function ( name ) { for ( var i = 0, il = this.bones.length; i < il; i ++ ) { var bone = this.bones[ i ]; if ( bone.name === name ) { return bone; } } return undefined; } } ); /** * @author mikael emtinger / http://gomo.se/ * @author alteredq / http://alteredqualia.com/ * @author ikerr / http://verold.com */ function Bone() { Object3D.call( this ); this.type = 'Bone'; } Bone.prototype = Object.assign( Object.create( Object3D.prototype ), { constructor: Bone, isBone: true } ); /** * @author mrdoob / http://mrdoob.com/ */ var _instanceLocalMatrix = new Matrix4(); var _instanceWorldMatrix = new Matrix4(); var _instanceIntersects = []; var _mesh = new Mesh(); function InstancedMesh( geometry, material, count ) { Mesh.call( this, geometry, material ); this.instanceMatrix = new BufferAttribute( new Float32Array( count * 16 ), 16 ); this.count = count; this.frustumCulled = false; } InstancedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), { constructor: InstancedMesh, isInstancedMesh: true, getMatrixAt: function ( index, matrix ) { matrix.fromArray( this.instanceMatrix.array, index * 16 ); }, raycast: function ( raycaster, intersects ) { var matrixWorld = this.matrixWorld; var raycastTimes = this.count; _mesh.geometry = this.geometry; _mesh.material = this.material; if ( _mesh.material === undefined ) { return; } for ( var instanceId = 0; instanceId < raycastTimes; instanceId ++ ) { // calculate the world matrix for each instance this.getMatrixAt( instanceId, _instanceLocalMatrix ); _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix ); // the mesh represents this single instance _mesh.matrixWorld = _instanceWorldMatrix; _mesh.raycast( raycaster, _instanceIntersects ); // process the result of raycast if ( _instanceIntersects.length > 0 ) { _instanceIntersects[ 0 ].instanceId = instanceId; _instanceIntersects[ 0 ].object = this; intersects.push( _instanceIntersects[ 0 ] ); _instanceIntersects.length = 0; } } }, setMatrixAt: function ( index, matrix ) { matrix.toArray( this.instanceMatrix.array, index * 16 ); }, updateMorphTargets: function () { } } ); /** * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ * * parameters = { * color: , * opacity: , * * linewidth: , * linecap: "round", * linejoin: "round" * } */ function LineBasicMaterial( parameters ) { Material.call( this ); this.type = 'LineBasicMaterial'; this.color = new Color( 0xffffff ); this.linewidth = 1; this.linecap = 'round'; this.linejoin = 'round'; this.setValues( parameters ); } LineBasicMaterial.prototype = Object.create( Material.prototype ); LineBasicMaterial.prototype.constructor = LineBasicMaterial; LineBasicMaterial.prototype.isLineBasicMaterial = true; LineBasicMaterial.prototype.copy = function ( source ) { Material.prototype.copy.call( this, source ); this.color.copy( source.color ); this.linewidth = source.linewidth; this.linecap = source.linecap; this.linejoin = source.linejoin; return this; }; /** * @author mrdoob / http://mrdoob.com/ */ var _start = new Vector3(); var _end = new Vector3(); var _inverseMatrix$1 = new Matrix4(); var _ray$1 = new Ray(); var _sphere$2 = new Sphere(); function Line( geometry, material, mode ) { if ( mode === 1 ) { console.error( 'THREE.Line: parameter THREE.LinePieces no longer supported. Use THREE.LineSegments instead.' ); } Object3D.call( this ); this.type = 'Line'; this.geometry = geometry !== undefined ? geometry : new BufferGeometry(); this.material = material !== undefined ? material : new LineBasicMaterial(); } Line.prototype = Object.assign( Object.create( Object3D.prototype ), { constructor: Line, isLine: true, computeLineDistances: function () { var geometry = this.geometry; if ( geometry.isBufferGeometry ) { // we assume non-indexed geometry if ( geometry.index === null ) { var positionAttribute = geometry.attributes.position; var lineDistances = [ 0 ]; for ( var i = 1, l = positionAttribute.count; i < l; i ++ ) { _start.fromBufferAttribute( positionAttribute, i - 1 ); _end.fromBufferAttribute( positionAttribute, i ); lineDistances[ i ] = lineDistances[ i - 1 ]; lineDistances[ i ] += _start.distanceTo( _end ); } geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) ); } else { console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' ); } } else if ( geometry.isGeometry ) { var vertices = geometry.vertices; var lineDistances = geometry.lineDistances; lineDistances[ 0 ] = 0; for ( var i = 1, l = vertices.length; i < l; i ++ ) { lineDistances[ i ] = lineDistances[ i - 1 ]; lineDistances[ i ] += vertices[ i - 1 ].distanceTo( vertices[ i ] ); } } return this; }, raycast: function ( raycaster, intersects ) { var precision = raycaster.linePrecision; var geometry = this.geometry; var matrixWorld = this.matrixWorld; // Checking boundingSphere distance to ray if ( geometry.boundingSphere === null ) { geometry.computeBoundingSphere(); } _sphere$2.copy( geometry.boundingSphere ); _sphere$2.applyMatrix4( matrixWorld ); _sphere$2.radius += precision; if ( raycaster.ray.intersectsSphere( _sphere$2 ) === false ) { return; } // _inverseMatrix$1.getInverse( matrixWorld ); _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 ); var localPrecision = precision / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 ); var localPrecisionSq = localPrecision * localPrecision; var vStart = new Vector3(); var vEnd = new Vector3(); var interSegment = new Vector3(); var interRay = new Vector3(); var step = ( this && this.isLineSegments ) ? 2 : 1; if ( geometry.isBufferGeometry ) { var index = geometry.index; var attributes = geometry.attributes; var positions = attributes.position.array; if ( index !== null ) { var indices = index.array; for ( var i = 0, l = indices.length - 1; i < l; i += step ) { var a = indices[ i ]; var b = indices[ i + 1 ]; vStart.fromArray( positions, a * 3 ); vEnd.fromArray( positions, b * 3 ); var distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment ); if ( distSq > localPrecisionSq ) { continue; } interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation var distance = raycaster.ray.origin.distanceTo( interRay ); if ( distance < raycaster.near || distance > raycaster.far ) { continue; } intersects.push( { distance: distance, // What do we want? intersection point on the ray or on the segment?? // point: raycaster.ray.at( distance ), point: interSegment.clone().applyMatrix4( this.matrixWorld ), index: i, face: null, faceIndex: null, object: this } ); } } else { for ( var i = 0, l = positions.length / 3 - 1; i < l; i += step ) { vStart.fromArray( positions, 3 * i ); vEnd.fromArray( positions, 3 * i + 3 ); var distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment ); if ( distSq > localPrecisionSq ) { continue; } interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation var distance = raycaster.ray.origin.distanceTo( interRay ); if ( distance < raycaster.near || distance > raycaster.far ) { continue; } intersects.push( { distance: distance, // What do we want? intersection point on the ray or on the segment?? // point: raycaster.ray.at( distance ), point: interSegment.clone().applyMatrix4( this.matrixWorld ), index: i, face: null, faceIndex: null, object: this } ); } } } else if ( geometry.isGeometry ) { var vertices = geometry.vertices; var nbVertices = vertices.length; for ( var i = 0; i < nbVertices - 1; i += step ) { var distSq = _ray$1.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment ); if ( distSq > localPrecisionSq ) { continue; } interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation var distance = raycaster.ray.origin.distanceTo( interRay ); if ( distance < raycaster.near || distance > raycaster.far ) { continue; } intersects.push( { distance: distance, // What do we want? intersection point on the ray or on the segment?? // point: raycaster.ray.at( distance ), point: interSegment.clone().applyMatrix4( this.matrixWorld ), index: i, face: null, faceIndex: null, object: this } ); } } }, clone: function () { return new this.constructor( this.geometry, this.material ).copy( this ); } } ); /** * @author mrdoob / http://mrdoob.com/ */ var _start$1 = new Vector3(); var _end$1 = new Vector3(); function LineSegments( geometry, material ) { Line.call( this, geometry, material ); this.type = 'LineSegments'; } LineSegments.prototype = Object.assign( Object.create( Line.prototype ), { constructor: LineSegments, isLineSegments: true, computeLineDistances: function () { var geometry = this.geometry; if ( geometry.isBufferGeometry ) { // we assume non-indexed geometry if ( geometry.index === null ) { var positionAttribute = geometry.attributes.position; var lineDistances = []; for ( var i = 0, l = positionAttribute.count; i < l; i += 2 ) { _start$1.fromBufferAttribute( positionAttribute, i ); _end$1.fromBufferAttribute( positionAttribute, i + 1 ); lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ]; lineDistances[ i + 1 ] = lineDistances[ i ] + _start$1.distanceTo( _end$1 ); } geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) ); } else { console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' ); } } else if ( geometry.isGeometry ) { var vertices = geometry.vertices; var lineDistances = geometry.lineDistances; for ( var i = 0, l = vertices.length; i < l; i += 2 ) { _start$1.copy( vertices[ i ] ); _end$1.copy( vertices[ i + 1 ] ); lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ]; lineDistances[ i + 1 ] = lineDistances[ i ] + _start$1.distanceTo( _end$1 ); } } return this; } } ); /** * @author mgreter / http://github.com/mgreter */ function LineLoop( geometry, material ) { Line.call( this, geometry, material ); this.type = 'LineLoop'; } LineLoop.prototype = Object.assign( Object.create( Line.prototype ), { constructor: LineLoop, isLineLoop: true, } ); /** * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ * * parameters = { * color: , * opacity: , * map: new THREE.Texture( ), * alphaMap: new THREE.Texture( ), * * size: , * sizeAttenuation: * * morphTargets: * } */ function PointsMaterial( parameters ) { Material.call( this ); this.type = 'PointsMaterial'; this.color = new Color( 0xffffff ); this.map = null; this.alphaMap = null; this.size = 1; this.sizeAttenuation = true; this.morphTargets = false; this.setValues( parameters ); } PointsMaterial.prototype = Object.create( Material.prototype ); PointsMaterial.prototype.constructor = PointsMaterial; PointsMaterial.prototype.isPointsMaterial = true; PointsMaterial.prototype.copy = function ( source ) { Material.prototype.copy.call( this, source ); this.color.copy( source.color ); this.map = source.map; this.alphaMap = source.alphaMap; this.size = source.size; this.sizeAttenuation = source.sizeAttenuation; this.morphTargets = source.morphTargets; return this; }; /** * @author alteredq / http://alteredqualia.com/ */ var _inverseMatrix$2 = new Matrix4(); var _ray$2 = new Ray(); var _sphere$3 = new Sphere(); var _position$1 = new Vector3(); function Points( geometry, material ) { Object3D.call( this ); this.type = 'Points'; this.geometry = geometry !== undefined ? geometry : new BufferGeometry(); this.material = material !== undefined ? material : new PointsMaterial(); this.updateMorphTargets(); } Points.prototype = Object.assign( Object.create( Object3D.prototype ), { constructor: Points, isPoints: true, raycast: function ( raycaster, intersects ) { var geometry = this.geometry; var matrixWorld = this.matrixWorld; var threshold = raycaster.params.Points.threshold; // Checking boundingSphere distance to ray if ( geometry.boundingSphere === null ) { geometry.computeBoundingSphere(); } _sphere$3.copy( geometry.boundingSphere ); _sphere$3.applyMatrix4( matrixWorld ); _sphere$3.radius += threshold; if ( raycaster.ray.intersectsSphere( _sphere$3 ) === false ) { return; } // _inverseMatrix$2.getInverse( matrixWorld ); _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 ); var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 ); var localThresholdSq = localThreshold * localThreshold; if ( geometry.isBufferGeometry ) { var index = geometry.index; var attributes = geometry.attributes; var positions = attributes.position.array; if ( index !== null ) { var indices = index.array; for ( var i = 0, il = indices.length; i < il; i ++ ) { var a = indices[ i ]; _position$1.fromArray( positions, a * 3 ); testPoint( _position$1, a, localThresholdSq, matrixWorld, raycaster, intersects, this ); } } else { for ( var i = 0, l = positions.length / 3; i < l; i ++ ) { _position$1.fromArray( positions, i * 3 ); testPoint( _position$1, i, localThresholdSq, matrixWorld, raycaster, intersects, this ); } } } else { var vertices = geometry.vertices; for ( var i = 0, l = vertices.length; i < l; i ++ ) { testPoint( vertices[ i ], i, localThresholdSq, matrixWorld, raycaster, intersects, this ); } } }, updateMorphTargets: function () { var geometry = this.geometry; var m, ml, name; if ( geometry.isBufferGeometry ) { var morphAttributes = geometry.morphAttributes; var keys = Object.keys( morphAttributes ); if ( keys.length > 0 ) { var morphAttribute = morphAttributes[ keys[ 0 ] ]; if ( morphAttribute !== undefined ) { this.morphTargetInfluences = []; this.morphTargetDictionary = {}; for ( m = 0, ml = morphAttribute.length; m < ml; m ++ ) { name = morphAttribute[ m ].name || String( m ); this.morphTargetInfluences.push( 0 ); this.morphTargetDictionary[ name ] = m; } } } } else { var morphTargets = geometry.morphTargets; if ( morphTargets !== undefined && morphTargets.length > 0 ) { console.error( 'THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.' ); } } }, clone: function () { return new this.constructor( this.geometry, this.material ).copy( this ); } } ); function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) { var rayPointDistanceSq = _ray$2.distanceSqToPoint( point ); if ( rayPointDistanceSq < localThresholdSq ) { var intersectPoint = new Vector3(); _ray$2.closestPointToPoint( point, intersectPoint ); intersectPoint.applyMatrix4( matrixWorld ); var distance = raycaster.ray.origin.distanceTo( intersectPoint ); if ( distance < raycaster.near || distance > raycaster.far ) { return; } intersects.push( { distance: distance, distanceToRay: Math.sqrt( rayPointDistanceSq ), point: intersectPoint, index: index, face: null, object: object } ); } } /** * @author mrdoob / http://mrdoob.com/ */ function VideoTexture( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); this.format = format !== undefined ? format : RGBFormat; this.minFilter = minFilter !== undefined ? minFilter : LinearFilter; this.magFilter = magFilter !== undefined ? magFilter : LinearFilter; this.generateMipmaps = false; } VideoTexture.prototype = Object.assign( Object.create( Texture.prototype ), { constructor: VideoTexture, isVideoTexture: true, update: function () { var video = this.image; if ( video.readyState >= video.HAVE_CURRENT_DATA ) { this.needsUpdate = true; } } } ); /** * @author alteredq / http://alteredqualia.com/ */ function CompressedTexture( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) { Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ); this.image = { width: width, height: height }; this.mipmaps = mipmaps; // no flipping for cube textures // (also flipping doesn't work for compressed textures ) this.flipY = false; // can't generate mipmaps for compressed textures // mips must be embedded in DDS files this.generateMipmaps = false; } CompressedTexture.prototype = Object.create( Texture.prototype ); CompressedTexture.prototype.constructor = CompressedTexture; CompressedTexture.prototype.isCompressedTexture = true; /** * @author mrdoob / http://mrdoob.com/ */ function CanvasTexture( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) { Texture.call( this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); this.needsUpdate = true; } CanvasTexture.prototype = Object.create( Texture.prototype ); CanvasTexture.prototype.constructor = CanvasTexture; CanvasTexture.prototype.isCanvasTexture = true; /** * @author Matt DesLauriers / @mattdesl * @author atix / arthursilber.de */ function DepthTexture( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) { format = format !== undefined ? format : DepthFormat; if ( format !== DepthFormat && format !== DepthStencilFormat ) { throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' ); } if ( type === undefined && format === DepthFormat ) { type = UnsignedShortType; } if ( type === undefined && format === DepthStencilFormat ) { type = UnsignedInt248Type; } Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ); this.image = { width: width, height: height }; this.magFilter = magFilter !== undefined ? magFilter : NearestFilter; this.minFilter = minFilter !== undefined ? minFilter : NearestFilter; this.flipY = false; this.generateMipmaps = false; } DepthTexture.prototype = Object.create( Texture.prototype ); DepthTexture.prototype.constructor = DepthTexture; DepthTexture.prototype.isDepthTexture = true; /** * @author mrdoob / http://mrdoob.com/ * @author Mugen87 / https://github.com/Mugen87 */ function WireframeGeometry( geometry ) { BufferGeometry.call( this ); this.type = 'WireframeGeometry'; // buffer var vertices = []; // helper variables var i, j, l, o, ol; var edge = [ 0, 0 ], edges = {}, e, edge1, edge2; var key, keys = [ 'a', 'b', 'c' ]; var vertex; // different logic for Geometry and BufferGeometry if ( geometry && geometry.isGeometry ) { // create a data structure that contains all edges without duplicates var faces = geometry.faces; for ( i = 0, l = faces.length; i < l; i ++ ) { var face = faces[ i ]; for ( j = 0; j < 3; j ++ ) { edge1 = face[ keys[ j ] ]; edge2 = face[ keys[ ( j + 1 ) % 3 ] ]; edge[ 0 ] = Math.min( edge1, edge2 ); // sorting prevents duplicates edge[ 1 ] = Math.max( edge1, edge2 ); key = edge[ 0 ] + ',' + edge[ 1 ]; if ( edges[ key ] === undefined ) { edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ] }; } } } // generate vertices for ( key in edges ) { e = edges[ key ]; vertex = geometry.vertices[ e.index1 ]; vertices.push( vertex.x, vertex.y, vertex.z ); vertex = geometry.vertices[ e.index2 ]; vertices.push( vertex.x, vertex.y, vertex.z ); } } else if ( geometry && geometry.isBufferGeometry ) { var position, indices, groups; var group, start, count; var index1, index2; vertex = new Vector3(); if ( geometry.index !== null ) { // indexed BufferGeometry position = geometry.attributes.position; indices = geometry.index; groups = geometry.groups; if ( groups.length === 0 ) { groups = [ { start: 0, count: indices.count, materialIndex: 0 } ]; } // create a data structure that contains all eges without duplicates for ( o = 0, ol = groups.length; o < ol; ++ o ) { group = groups[ o ]; start = group.start; count = group.count; for ( i = start, l = ( start + count ); i < l; i += 3 ) { for ( j = 0; j < 3; j ++ ) { edge1 = indices.getX( i + j ); edge2 = indices.getX( i + ( j + 1 ) % 3 ); edge[ 0 ] = Math.min( edge1, edge2 ); // sorting prevents duplicates edge[ 1 ] = Math.max( edge1, edge2 ); key = edge[ 0 ] + ',' + edge[ 1 ]; if ( edges[ key ] === undefined ) { edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ] }; } } } } // generate vertices for ( key in edges ) { e = edges[ key ]; vertex.fromBufferAttribute( position, e.index1 ); vertices.push( vertex.x, vertex.y, vertex.z ); vertex.fromBufferAttribute( position, e.index2 ); vertices.push( vertex.x, vertex.y, vertex.z ); } } else { // non-indexed BufferGeometry position = geometry.attributes.position; for ( i = 0, l = ( position.count / 3 ); i < l; i ++ ) { for ( j = 0; j < 3; j ++ ) { // three edges per triangle, an edge is represented as (index1, index2) // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0) index1 = 3 * i + j; vertex.fromBufferAttribute( position, index1 ); vertices.push( vertex.x, vertex.y, vertex.z ); index2 = 3 * i + ( ( j + 1 ) % 3 ); vertex.fromBufferAttribute( position, index2 ); vertices.push( vertex.x, vertex.y, vertex.z ); } } } } // build geometry this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); } WireframeGeometry.prototype = Object.create( BufferGeometry.prototype ); WireframeGeometry.prototype.constructor = WireframeGeometry; /** * @author zz85 / https://github.com/zz85 * @author Mugen87 / https://github.com/Mugen87 * * Parametric Surfaces Geometry * based on the brilliant article by @prideout https://prideout.net/blog/old/blog/index.html@p=44.html */ // ParametricGeometry function ParametricGeometry( func, slices, stacks ) { Geometry.call( this ); this.type = 'ParametricGeometry'; this.parameters = { func: func, slices: slices, stacks: stacks }; this.fromBufferGeometry( new ParametricBufferGeometry( func, slices, stacks ) ); this.mergeVertices(); } ParametricGeometry.prototype = Object.create( Geometry.prototype ); ParametricGeometry.prototype.constructor = ParametricGeometry; // ParametricBufferGeometry function ParametricBufferGeometry( func, slices, stacks ) { BufferGeometry.call( this ); this.type = 'ParametricBufferGeometry'; this.parameters = { func: func, slices: slices, stacks: stacks }; // buffers var indices = []; var vertices = []; var normals = []; var uvs = []; var EPS = 0.00001; var normal = new Vector3(); var p0 = new Vector3(), p1 = new Vector3(); var pu = new Vector3(), pv = new Vector3(); var i, j; if ( func.length < 3 ) { console.error( 'THREE.ParametricGeometry: Function must now modify a Vector3 as third parameter.' ); } // generate vertices, normals and uvs var sliceCount = slices + 1; for ( i = 0; i <= stacks; i ++ ) { var v = i / stacks; for ( j = 0; j <= slices; j ++ ) { var u = j / slices; // vertex func( u, v, p0 ); vertices.push( p0.x, p0.y, p0.z ); // normal // approximate tangent vectors via finite differences if ( u - EPS >= 0 ) { func( u - EPS, v, p1 ); pu.subVectors( p0, p1 ); } else { func( u + EPS, v, p1 ); pu.subVectors( p1, p0 ); } if ( v - EPS >= 0 ) { func( u, v - EPS, p1 ); pv.subVectors( p0, p1 ); } else { func( u, v + EPS, p1 ); pv.subVectors( p1, p0 ); } // cross product of tangent vectors returns surface normal normal.crossVectors( pu, pv ).normalize(); normals.push( normal.x, normal.y, normal.z ); // uv uvs.push( u, v ); } } // generate indices for ( i = 0; i < stacks; i ++ ) { for ( j = 0; j < slices; j ++ ) { var a = i * sliceCount + j; var b = i * sliceCount + j + 1; var c = ( i + 1 ) * sliceCount + j + 1; var d = ( i + 1 ) * sliceCount + j; // faces one and two indices.push( a, b, d ); indices.push( b, c, d ); } } // build geometry this.setIndex( indices ); this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); } ParametricBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); ParametricBufferGeometry.prototype.constructor = ParametricBufferGeometry; /** * @author clockworkgeek / https://github.com/clockworkgeek * @author timothypratley / https://github.com/timothypratley * @author WestLangley / http://github.com/WestLangley * @author Mugen87 / https://github.com/Mugen87 */ // PolyhedronGeometry function PolyhedronGeometry( vertices, indices, radius, detail ) { Geometry.call( this ); this.type = 'PolyhedronGeometry'; this.parameters = { vertices: vertices, indices: indices, radius: radius, detail: detail }; this.fromBufferGeometry( new PolyhedronBufferGeometry( vertices, indices, radius, detail ) ); this.mergeVertices(); } PolyhedronGeometry.prototype = Object.create( Geometry.prototype ); PolyhedronGeometry.prototype.constructor = PolyhedronGeometry; // PolyhedronBufferGeometry function PolyhedronBufferGeometry( vertices, indices, radius, detail ) { BufferGeometry.call( this ); this.type = 'PolyhedronBufferGeometry'; this.parameters = { vertices: vertices, indices: indices, radius: radius, detail: detail }; radius = radius || 1; detail = detail || 0; // default buffer data var vertexBuffer = []; var uvBuffer = []; // the subdivision creates the vertex buffer data subdivide( detail ); // all vertices should lie on a conceptual sphere with a given radius applyRadius( radius ); // finally, create the uv data generateUVs(); // build non-indexed geometry this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) ); this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) ); this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) ); if ( detail === 0 ) { this.computeVertexNormals(); // flat normals } else { this.normalizeNormals(); // smooth normals } // helper functions function subdivide( detail ) { var a = new Vector3(); var b = new Vector3(); var c = new Vector3(); // iterate over all faces and apply a subdivison with the given detail value for ( var i = 0; i < indices.length; i += 3 ) { // get the vertices of the face getVertexByIndex( indices[ i + 0 ], a ); getVertexByIndex( indices[ i + 1 ], b ); getVertexByIndex( indices[ i + 2 ], c ); // perform subdivision subdivideFace( a, b, c, detail ); } } function subdivideFace( a, b, c, detail ) { var cols = Math.pow( 2, detail ); // we use this multidimensional array as a data structure for creating the subdivision var v = []; var i, j; // construct all of the vertices for this subdivision for ( i = 0; i <= cols; i ++ ) { v[ i ] = []; var aj = a.clone().lerp( c, i / cols ); var bj = b.clone().lerp( c, i / cols ); var rows = cols - i; for ( j = 0; j <= rows; j ++ ) { if ( j === 0 && i === cols ) { v[ i ][ j ] = aj; } else { v[ i ][ j ] = aj.clone().lerp( bj, j / rows ); } } } // construct all of the faces for ( i = 0; i < cols; i ++ ) { for ( j = 0; j < 2 * ( cols - i ) - 1; j ++ ) { var k = Math.floor( j / 2 ); if ( j % 2 === 0 ) { pushVertex( v[ i ][ k + 1 ] ); pushVertex( v[ i + 1 ][ k ] ); pushVertex( v[ i ][ k ] ); } else { pushVertex( v[ i ][ k + 1 ] ); pushVertex( v[ i + 1 ][ k + 1 ] ); pushVertex( v[ i + 1 ][ k ] ); } } } } function applyRadius( radius ) { var vertex = new Vector3(); // iterate over the entire buffer and apply the radius to each vertex for ( var i = 0; i < vertexBuffer.length; i += 3 ) { vertex.x = vertexBuffer[ i + 0 ]; vertex.y = vertexBuffer[ i + 1 ]; vertex.z = vertexBuffer[ i + 2 ]; vertex.normalize().multiplyScalar( radius ); vertexBuffer[ i + 0 ] = vertex.x; vertexBuffer[ i + 1 ] = vertex.y; vertexBuffer[ i + 2 ] = vertex.z; } } function generateUVs() { var vertex = new Vector3(); for ( var i = 0; i < vertexBuffer.length; i += 3 ) { vertex.x = vertexBuffer[ i + 0 ]; vertex.y = vertexBuffer[ i + 1 ]; vertex.z = vertexBuffer[ i + 2 ]; var u = azimuth( vertex ) / 2 / Math.PI + 0.5; var v = inclination( vertex ) / Math.PI + 0.5; uvBuffer.push( u, 1 - v ); } correctUVs(); correctSeam(); } function correctSeam() { // handle case when face straddles the seam, see #3269 for ( var i = 0; i < uvBuffer.length; i += 6 ) { // uv data of a single face var x0 = uvBuffer[ i + 0 ]; var x1 = uvBuffer[ i + 2 ]; var x2 = uvBuffer[ i + 4 ]; var max = Math.max( x0, x1, x2 ); var min = Math.min( x0, x1, x2 ); // 0.9 is somewhat arbitrary if ( max > 0.9 && min < 0.1 ) { if ( x0 < 0.2 ) { uvBuffer[ i + 0 ] += 1; } if ( x1 < 0.2 ) { uvBuffer[ i + 2 ] += 1; } if ( x2 < 0.2 ) { uvBuffer[ i + 4 ] += 1; } } } } function pushVertex( vertex ) { vertexBuffer.push( vertex.x, vertex.y, vertex.z ); } function getVertexByIndex( index, vertex ) { var stride = index * 3; vertex.x = vertices[ stride + 0 ]; vertex.y = vertices[ stride + 1 ]; vertex.z = vertices[ stride + 2 ]; } function correctUVs() { var a = new Vector3(); var b = new Vector3(); var c = new Vector3(); var centroid = new Vector3(); var uvA = new Vector2(); var uvB = new Vector2(); var uvC = new Vector2(); for ( var i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) { a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] ); b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] ); c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] ); uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] ); uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] ); uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] ); centroid.copy( a ).add( b ).add( c ).divideScalar( 3 ); var azi = azimuth( centroid ); correctUV( uvA, j + 0, a, azi ); correctUV( uvB, j + 2, b, azi ); correctUV( uvC, j + 4, c, azi ); } } function correctUV( uv, stride, vector, azimuth ) { if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) { uvBuffer[ stride ] = uv.x - 1; } if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) { uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5; } } // Angle around the Y axis, counter-clockwise when looking from above. function azimuth( vector ) { return Math.atan2( vector.z, - vector.x ); } // Angle above the XZ plane. function inclination( vector ) { return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) ); } } PolyhedronBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); PolyhedronBufferGeometry.prototype.constructor = PolyhedronBufferGeometry; /** * @author timothypratley / https://github.com/timothypratley * @author Mugen87 / https://github.com/Mugen87 */ // TetrahedronGeometry function TetrahedronGeometry( radius, detail ) { Geometry.call( this ); this.type = 'TetrahedronGeometry'; this.parameters = { radius: radius, detail: detail }; this.fromBufferGeometry( new TetrahedronBufferGeometry( radius, detail ) ); this.mergeVertices(); } TetrahedronGeometry.prototype = Object.create( Geometry.prototype ); TetrahedronGeometry.prototype.constructor = TetrahedronGeometry; // TetrahedronBufferGeometry function TetrahedronBufferGeometry( radius, detail ) { var vertices = [ 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1 ]; var indices = [ 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1 ]; PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail ); this.type = 'TetrahedronBufferGeometry'; this.parameters = { radius: radius, detail: detail }; } TetrahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype ); TetrahedronBufferGeometry.prototype.constructor = TetrahedronBufferGeometry; /** * @author timothypratley / https://github.com/timothypratley * @author Mugen87 / https://github.com/Mugen87 */ // OctahedronGeometry function OctahedronGeometry( radius, detail ) { Geometry.call( this ); this.type = 'OctahedronGeometry'; this.parameters = { radius: radius, detail: detail }; this.fromBufferGeometry( new OctahedronBufferGeometry( radius, detail ) ); this.mergeVertices(); } OctahedronGeometry.prototype = Object.create( Geometry.prototype ); OctahedronGeometry.prototype.constructor = OctahedronGeometry; // OctahedronBufferGeometry function OctahedronBufferGeometry( radius, detail ) { var vertices = [ 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1 ]; var indices = [ 0, 2, 4, 0, 4, 3, 0, 3, 5, 0, 5, 2, 1, 2, 5, 1, 5, 3, 1, 3, 4, 1, 4, 2 ]; PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail ); this.type = 'OctahedronBufferGeometry'; this.parameters = { radius: radius, detail: detail }; } OctahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype ); OctahedronBufferGeometry.prototype.constructor = OctahedronBufferGeometry; /** * @author timothypratley / https://github.com/timothypratley * @author Mugen87 / https://github.com/Mugen87 */ // IcosahedronGeometry function IcosahedronGeometry( radius, detail ) { Geometry.call( this ); this.type = 'IcosahedronGeometry'; this.parameters = { radius: radius, detail: detail }; this.fromBufferGeometry( new IcosahedronBufferGeometry( radius, detail ) ); this.mergeVertices(); } IcosahedronGeometry.prototype = Object.create( Geometry.prototype ); IcosahedronGeometry.prototype.constructor = IcosahedronGeometry; // IcosahedronBufferGeometry function IcosahedronBufferGeometry( radius, detail ) { var t = ( 1 + Math.sqrt( 5 ) ) / 2; var 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 ]; var indices = [ 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11, 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8, 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9, 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1 ]; PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail ); this.type = 'IcosahedronBufferGeometry'; this.parameters = { radius: radius, detail: detail }; } IcosahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype ); IcosahedronBufferGeometry.prototype.constructor = IcosahedronBufferGeometry; /** * @author Abe Pazos / https://hamoid.com * @author Mugen87 / https://github.com/Mugen87 */ // DodecahedronGeometry function DodecahedronGeometry( radius, detail ) { Geometry.call( this ); this.type = 'DodecahedronGeometry'; this.parameters = { radius: radius, detail: detail }; this.fromBufferGeometry( new DodecahedronBufferGeometry( radius, detail ) ); this.mergeVertices(); } DodecahedronGeometry.prototype = Object.create( Geometry.prototype ); DodecahedronGeometry.prototype.constructor = DodecahedronGeometry; // DodecahedronBufferGeometry function DodecahedronBufferGeometry( radius, detail ) { var t = ( 1 + Math.sqrt( 5 ) ) / 2; var r = 1 / t; var vertices = [ // (±1, ±1, ±1) - 1, - 1, - 1, - 1, - 1, 1, - 1, 1, - 1, - 1, 1, 1, 1, - 1, - 1, 1, - 1, 1, 1, 1, - 1, 1, 1, 1, // (0, ±1/φ, ±φ) 0, - r, - t, 0, - r, t, 0, r, - t, 0, r, t, // (±1/φ, ±φ, 0) - r, - t, 0, - r, t, 0, r, - t, 0, r, t, 0, // (±φ, 0, ±1/φ) - t, 0, - r, t, 0, - r, - t, 0, r, t, 0, r ]; var indices = [ 3, 11, 7, 3, 7, 15, 3, 15, 13, 7, 19, 17, 7, 17, 6, 7, 6, 15, 17, 4, 8, 17, 8, 10, 17, 10, 6, 8, 0, 16, 8, 16, 2, 8, 2, 10, 0, 12, 1, 0, 1, 18, 0, 18, 16, 6, 10, 2, 6, 2, 13, 6, 13, 15, 2, 16, 18, 2, 18, 3, 2, 3, 13, 18, 1, 9, 18, 9, 11, 18, 11, 3, 4, 14, 12, 4, 12, 0, 4, 0, 8, 11, 9, 5, 11, 5, 19, 11, 19, 7, 19, 5, 14, 19, 14, 4, 19, 4, 17, 1, 12, 14, 1, 14, 5, 1, 5, 9 ]; PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail ); this.type = 'DodecahedronBufferGeometry'; this.parameters = { radius: radius, detail: detail }; } DodecahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype ); DodecahedronBufferGeometry.prototype.constructor = DodecahedronBufferGeometry; /** * @author oosmoxiecode / https://github.com/oosmoxiecode * @author WestLangley / https://github.com/WestLangley * @author zz85 / https://github.com/zz85 * @author miningold / https://github.com/miningold * @author jonobr1 / https://github.com/jonobr1 * @author Mugen87 / https://github.com/Mugen87 * */ // TubeGeometry function TubeGeometry( path, tubularSegments, radius, radialSegments, closed, taper ) { Geometry.call( this ); this.type = 'TubeGeometry'; this.parameters = { path: path, tubularSegments: tubularSegments, radius: radius, radialSegments: radialSegments, closed: closed }; if ( taper !== undefined ) { console.warn( 'THREE.TubeGeometry: taper has been removed.' ); } var bufferGeometry = new TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed ); // expose internals this.tangents = bufferGeometry.tangents; this.normals = bufferGeometry.normals; this.binormals = bufferGeometry.binormals; // create geometry this.fromBufferGeometry( bufferGeometry ); this.mergeVertices(); } TubeGeometry.prototype = Object.create( Geometry.prototype ); TubeGeometry.prototype.constructor = TubeGeometry; // TubeBufferGeometry function TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed ) { BufferGeometry.call( this ); this.type = 'TubeBufferGeometry'; this.parameters = { path: path, tubularSegments: tubularSegments, radius: radius, radialSegments: radialSegments, closed: closed }; tubularSegments = tubularSegments || 64; radius = radius || 1; radialSegments = radialSegments || 8; closed = closed || false; var frames = path.computeFrenetFrames( tubularSegments, closed ); // expose internals this.tangents = frames.tangents; this.normals = frames.normals; this.binormals = frames.binormals; // helper variables var vertex = new Vector3(); var normal = new Vector3(); var uv = new Vector2(); var P = new Vector3(); var i, j; // buffer var vertices = []; var normals = []; var uvs = []; var indices = []; // create buffer data generateBufferData(); // build geometry this.setIndex( indices ); this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); // functions function generateBufferData() { for ( i = 0; i < tubularSegments; i ++ ) { generateSegment( i ); } // if the geometry is not closed, generate the last row of vertices and normals // at the regular position on the given path // // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ) generateSegment( ( closed === false ) ? tubularSegments : 0 ); // uvs are generated in a separate function. // this makes it easy compute correct values for closed geometries generateUVs(); // finally create faces generateIndices(); } function generateSegment( i ) { // we use getPointAt to sample evenly distributed points from the given path P = path.getPointAt( i / tubularSegments, P ); // retrieve corresponding normal and binormal var N = frames.normals[ i ]; var B = frames.binormals[ i ]; // generate normals and vertices for the current segment for ( j = 0; j <= radialSegments; j ++ ) { var v = j / radialSegments * Math.PI * 2; var sin = Math.sin( v ); var cos = - Math.cos( v ); // normal normal.x = ( cos * N.x + sin * B.x ); normal.y = ( cos * N.y + sin * B.y ); normal.z = ( cos * N.z + sin * B.z ); normal.normalize(); normals.push( normal.x, normal.y, normal.z ); // vertex vertex.x = P.x + radius * normal.x; vertex.y = P.y + radius * normal.y; vertex.z = P.z + radius * normal.z; vertices.push( vertex.x, vertex.y, vertex.z ); } } function generateIndices() { for ( j = 1; j <= tubularSegments; j ++ ) { for ( i = 1; i <= radialSegments; i ++ ) { var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 ); var b = ( radialSegments + 1 ) * j + ( i - 1 ); var c = ( radialSegments + 1 ) * j + i; var d = ( radialSegments + 1 ) * ( j - 1 ) + i; // faces indices.push( a, b, d ); indices.push( b, c, d ); } } } function generateUVs() { for ( i = 0; i <= tubularSegments; i ++ ) { for ( j = 0; j <= radialSegments; j ++ ) { uv.x = i / tubularSegments; uv.y = j / radialSegments; uvs.push( uv.x, uv.y ); } } } } TubeBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); TubeBufferGeometry.prototype.constructor = TubeBufferGeometry; TubeBufferGeometry.prototype.toJSON = function () { var data = BufferGeometry.prototype.toJSON.call( this ); data.path = this.parameters.path.toJSON(); return data; }; /** * @author oosmoxiecode * @author Mugen87 / https://github.com/Mugen87 * * based on http://www.blackpawn.com/texts/pqtorus/ */ // TorusKnotGeometry function TorusKnotGeometry( radius, tube, tubularSegments, radialSegments, p, q, heightScale ) { Geometry.call( this ); this.type = 'TorusKnotGeometry'; this.parameters = { radius: radius, tube: tube, tubularSegments: tubularSegments, radialSegments: radialSegments, p: p, q: q }; if ( heightScale !== undefined ) { console.warn( 'THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.' ); } this.fromBufferGeometry( new TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) ); this.mergeVertices(); } TorusKnotGeometry.prototype = Object.create( Geometry.prototype ); TorusKnotGeometry.prototype.constructor = TorusKnotGeometry; // TorusKnotBufferGeometry function TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) { BufferGeometry.call( this ); this.type = 'TorusKnotBufferGeometry'; this.parameters = { radius: radius, tube: tube, tubularSegments: tubularSegments, radialSegments: radialSegments, p: p, q: q }; radius = radius || 1; tube = tube || 0.4; tubularSegments = Math.floor( tubularSegments ) || 64; radialSegments = Math.floor( radialSegments ) || 8; p = p || 2; q = q || 3; // buffers var indices = []; var vertices = []; var normals = []; var uvs = []; // helper variables var i, j; var vertex = new Vector3(); var normal = new Vector3(); var P1 = new Vector3(); var P2 = new Vector3(); var B = new Vector3(); var T = new Vector3(); var N = new Vector3(); // generate vertices, normals and uvs for ( i = 0; i <= tubularSegments; ++ i ) { // the radian "u" is used to calculate the position on the torus curve of the current tubular segement var u = i / tubularSegments * p * Math.PI * 2; // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions calculatePositionOnCurve( u, p, q, radius, P1 ); calculatePositionOnCurve( u + 0.01, p, q, radius, P2 ); // calculate orthonormal basis T.subVectors( P2, P1 ); N.addVectors( P2, P1 ); B.crossVectors( T, N ); N.crossVectors( B, T ); // normalize B, N. T can be ignored, we don't use it B.normalize(); N.normalize(); for ( j = 0; j <= radialSegments; ++ j ) { // now calculate the vertices. they are nothing more than an extrusion of the torus curve. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value. var v = j / radialSegments * Math.PI * 2; var cx = - tube * Math.cos( v ); var cy = tube * Math.sin( v ); // now calculate the final vertex position. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve vertex.x = P1.x + ( cx * N.x + cy * B.x ); vertex.y = P1.y + ( cx * N.y + cy * B.y ); vertex.z = P1.z + ( cx * N.z + cy * B.z ); vertices.push( vertex.x, vertex.y, vertex.z ); // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal) normal.subVectors( vertex, P1 ).normalize(); normals.push( normal.x, normal.y, normal.z ); // uv uvs.push( i / tubularSegments ); uvs.push( j / radialSegments ); } } // generate indices for ( j = 1; j <= tubularSegments; j ++ ) { for ( i = 1; i <= radialSegments; i ++ ) { // indices var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 ); var b = ( radialSegments + 1 ) * j + ( i - 1 ); var c = ( radialSegments + 1 ) * j + i; var d = ( radialSegments + 1 ) * ( j - 1 ) + i; // faces indices.push( a, b, d ); indices.push( b, c, d ); } } // build geometry this.setIndex( indices ); this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); // this function calculates the current position on the torus curve function calculatePositionOnCurve( u, p, q, radius, position ) { var cu = Math.cos( u ); var su = Math.sin( u ); var quOverP = q / p * u; var cs = Math.cos( quOverP ); position.x = radius * ( 2 + cs ) * 0.5 * cu; position.y = radius * ( 2 + cs ) * su * 0.5; position.z = radius * Math.sin( quOverP ) * 0.5; } } TorusKnotBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); TorusKnotBufferGeometry.prototype.constructor = TorusKnotBufferGeometry; /** * @author oosmoxiecode * @author mrdoob / http://mrdoob.com/ * @author Mugen87 / https://github.com/Mugen87 */ // TorusGeometry function TorusGeometry( radius, tube, radialSegments, tubularSegments, arc ) { Geometry.call( this ); this.type = 'TorusGeometry'; this.parameters = { radius: radius, tube: tube, radialSegments: radialSegments, tubularSegments: tubularSegments, arc: arc }; this.fromBufferGeometry( new TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) ); this.mergeVertices(); } TorusGeometry.prototype = Object.create( Geometry.prototype ); TorusGeometry.prototype.constructor = TorusGeometry; // TorusBufferGeometry function TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) { BufferGeometry.call( this ); this.type = 'TorusBufferGeometry'; this.parameters = { radius: radius, tube: tube, radialSegments: radialSegments, tubularSegments: tubularSegments, arc: arc }; radius = radius || 1; tube = tube || 0.4; radialSegments = Math.floor( radialSegments ) || 8; tubularSegments = Math.floor( tubularSegments ) || 6; arc = arc || Math.PI * 2; // buffers var indices = []; var vertices = []; var normals = []; var uvs = []; // helper variables var center = new Vector3(); var vertex = new Vector3(); var normal = new Vector3(); var j, i; // generate vertices, normals and uvs for ( j = 0; j <= radialSegments; j ++ ) { for ( i = 0; i <= tubularSegments; i ++ ) { var u = i / tubularSegments * arc; var v = j / radialSegments * Math.PI * 2; // vertex vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u ); vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u ); vertex.z = tube * Math.sin( v ); vertices.push( vertex.x, vertex.y, vertex.z ); // normal center.x = radius * Math.cos( u ); center.y = radius * Math.sin( u ); normal.subVectors( vertex, center ).normalize(); normals.push( normal.x, normal.y, normal.z ); // uv uvs.push( i / tubularSegments ); uvs.push( j / radialSegments ); } } // generate indices for ( j = 1; j <= radialSegments; j ++ ) { for ( i = 1; i <= tubularSegments; i ++ ) { // indices var a = ( tubularSegments + 1 ) * j + i - 1; var b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1; var c = ( tubularSegments + 1 ) * ( j - 1 ) + i; var d = ( tubularSegments + 1 ) * j + i; // faces indices.push( a, b, d ); indices.push( b, c, d ); } } // build geometry this.setIndex( indices ); this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); } TorusBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); TorusBufferGeometry.prototype.constructor = TorusBufferGeometry; /** * @author Mugen87 / https://github.com/Mugen87 * Port from https://github.com/mapbox/earcut (v2.1.5) */ var Earcut = { triangulate: function ( data, holeIndices, dim ) { dim = dim || 2; var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length, outerNode = linkedList( data, 0, outerLen, dim, true ), triangles = []; if ( ! outerNode || outerNode.next === outerNode.prev ) { return triangles; } var minX, minY, maxX, maxY, x, y, invSize; if ( hasHoles ) { outerNode = eliminateHoles( data, holeIndices, outerNode, dim ); } // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox if ( data.length > 80 * dim ) { minX = maxX = data[ 0 ]; minY = maxY = data[ 1 ]; for ( var i = dim; i < outerLen; i += dim ) { x = data[ i ]; y = data[ i + 1 ]; if ( x < minX ) { minX = x; } if ( y < minY ) { minY = y; } if ( x > maxX ) { maxX = x; } if ( y > maxY ) { maxY = y; } } // minX, minY and invSize are later used to transform coords into integers for z-order calculation invSize = Math.max( maxX - minX, maxY - minY ); invSize = invSize !== 0 ? 1 / invSize : 0; } earcutLinked( outerNode, triangles, dim, minX, minY, invSize ); return triangles; } }; // create a circular doubly linked list from polygon points in the specified winding order function linkedList( data, start, end, dim, clockwise ) { var i, last; if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) { for ( i = start; i < end; i += dim ) { last = insertNode( i, data[ i ], data[ i + 1 ], last ); } } else { for ( i = end - dim; i >= start; i -= dim ) { last = insertNode( i, data[ i ], data[ i + 1 ], last ); } } if ( last && equals( last, last.next ) ) { removeNode( last ); last = last.next; } return last; } // eliminate colinear or duplicate points function filterPoints( start, end ) { if ( ! start ) { return start; } if ( ! end ) { end = start; } var p = start, again; do { again = false; if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) { removeNode( p ); p = end = p.prev; if ( p === p.next ) { break; } again = true; } else { p = p.next; } } while ( again || p !== end ); return end; } // main ear slicing loop which triangulates a polygon (given as a linked list) function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) { if ( ! ear ) { return; } // interlink polygon nodes in z-order if ( ! pass && invSize ) { indexCurve( ear, minX, minY, invSize ); } var stop = ear, prev, next; // iterate through ears, slicing them one by one while ( ear.prev !== ear.next ) { prev = ear.prev; next = ear.next; if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) { // cut off the triangle triangles.push( prev.i / dim ); triangles.push( ear.i / dim ); triangles.push( next.i / dim ); removeNode( ear ); // skipping the next vertex leads to less sliver triangles ear = next.next; stop = next.next; continue; } ear = next; // if we looped through the whole remaining polygon and can't find any more ears if ( ear === stop ) { // try filtering points and slicing again if ( ! pass ) { earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 ); // if this didn't work, try curing all small self-intersections locally } else if ( pass === 1 ) { ear = cureLocalIntersections( ear, triangles, dim ); earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 ); // as a last resort, try splitting the remaining polygon into two } else if ( pass === 2 ) { splitEarcut( ear, triangles, dim, minX, minY, invSize ); } break; } } } // check whether a polygon node forms a valid ear with adjacent nodes function isEar( ear ) { var a = ear.prev, b = ear, c = ear.next; if ( area( a, b, c ) >= 0 ) { return false; } // reflex, can't be an ear // now make sure we don't have other points inside the potential ear var p = ear.next.next; while ( p !== ear.prev ) { if ( pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) { return false; } p = p.next; } return true; } function isEarHashed( ear, minX, minY, invSize ) { var a = ear.prev, b = ear, c = ear.next; if ( area( a, b, c ) >= 0 ) { return false; } // reflex, can't be an ear // triangle bbox; min & max are calculated like this for speed var minTX = a.x < b.x ? ( a.x < c.x ? a.x : c.x ) : ( b.x < c.x ? b.x : c.x ), minTY = a.y < b.y ? ( a.y < c.y ? a.y : c.y ) : ( b.y < c.y ? b.y : c.y ), maxTX = a.x > b.x ? ( a.x > c.x ? a.x : c.x ) : ( b.x > c.x ? b.x : c.x ), maxTY = a.y > b.y ? ( a.y > c.y ? a.y : c.y ) : ( b.y > c.y ? b.y : c.y ); // z-order range for the current triangle bbox; var minZ = zOrder( minTX, minTY, minX, minY, invSize ), maxZ = zOrder( maxTX, maxTY, minX, minY, invSize ); var p = ear.prevZ, n = ear.nextZ; // look for points inside the triangle in both directions while ( p && p.z >= minZ && n && n.z <= maxZ ) { if ( p !== ear.prev && p !== ear.next && pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) { return false; } p = p.prevZ; if ( n !== ear.prev && n !== ear.next && pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) { return false; } n = n.nextZ; } // look for remaining points in decreasing z-order while ( p && p.z >= minZ ) { if ( p !== ear.prev && p !== ear.next && pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) { return false; } p = p.prevZ; } // look for remaining points in increasing z-order while ( n && n.z <= maxZ ) { if ( n !== ear.prev && n !== ear.next && pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) { return false; } n = n.nextZ; } return true; } // go through all polygon nodes and cure small local self-intersections function cureLocalIntersections( start, triangles, dim ) { var p = start; do { var a = p.prev, b = p.next.next; if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) { triangles.push( a.i / dim ); triangles.push( p.i / dim ); triangles.push( b.i / dim ); // remove two nodes involved removeNode( p ); removeNode( p.next ); p = start = b; } p = p.next; } while ( p !== start ); return p; } // try splitting polygon into two and triangulate them independently function splitEarcut( start, triangles, dim, minX, minY, invSize ) { // look for a valid diagonal that divides the polygon into two var a = start; do { var b = a.next.next; while ( b !== a.prev ) { if ( a.i !== b.i && isValidDiagonal( a, b ) ) { // split the polygon in two by the diagonal var c = splitPolygon( a, b ); // filter colinear points around the cuts a = filterPoints( a, a.next ); c = filterPoints( c, c.next ); // run earcut on each half earcutLinked( a, triangles, dim, minX, minY, invSize ); earcutLinked( c, triangles, dim, minX, minY, invSize ); return; } b = b.next; } a = a.next; } while ( a !== start ); } // link every hole into the outer loop, producing a single-ring polygon without holes function eliminateHoles( data, holeIndices, outerNode, dim ) { var queue = [], i, len, start, end, list; for ( i = 0, len = holeIndices.length; i < len; i ++ ) { start = holeIndices[ i ] * dim; end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length; list = linkedList( data, start, end, dim, false ); if ( list === list.next ) { list.steiner = true; } queue.push( getLeftmost( list ) ); } queue.sort( compareX ); // process holes from left to right for ( i = 0; i < queue.length; i ++ ) { eliminateHole( queue[ i ], outerNode ); outerNode = filterPoints( outerNode, outerNode.next ); } return outerNode; } function compareX( a, b ) { return a.x - b.x; } // find a bridge between vertices that connects hole with an outer ring and and link it function eliminateHole( hole, outerNode ) { outerNode = findHoleBridge( hole, outerNode ); if ( outerNode ) { var b = splitPolygon( outerNode, hole ); filterPoints( b, b.next ); } } // David Eberly's algorithm for finding a bridge between hole and outer polygon function findHoleBridge( hole, outerNode ) { var p = outerNode, hx = hole.x, hy = hole.y, qx = - Infinity, m; // find a segment intersected by a ray from the hole's leftmost point to the left; // segment's endpoint with lesser x will be potential connection point do { if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) { var x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y ); if ( x <= hx && x > qx ) { qx = x; if ( x === hx ) { if ( hy === p.y ) { return p; } if ( hy === p.next.y ) { return p.next; } } m = p.x < p.next.x ? p : p.next; } } p = p.next; } while ( p !== outerNode ); if ( ! m ) { return null; } if ( hx === qx ) { return m.prev; } // hole touches outer segment; pick lower endpoint // look for points inside the triangle of hole point, segment intersection and endpoint; // if there are no points found, we have a valid connection; // otherwise choose the point of the minimum angle with the ray as connection point var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan; p = m.next; while ( p !== stop ) { if ( hx >= p.x && p.x >= mx && hx !== p.x && pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) { tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential if ( ( tan < tanMin || ( tan === tanMin && p.x > m.x ) ) && locallyInside( p, hole ) ) { m = p; tanMin = tan; } } p = p.next; } return m; } // interlink polygon nodes in z-order function indexCurve( start, minX, minY, invSize ) { var p = start; do { if ( p.z === null ) { p.z = zOrder( p.x, p.y, minX, minY, invSize ); } p.prevZ = p.prev; p.nextZ = p.next; p = p.next; } while ( p !== start ); p.prevZ.nextZ = null; p.prevZ = null; sortLinked( p ); } // Simon Tatham's linked list merge sort algorithm // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html function sortLinked( list ) { var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1; do { p = list; list = null; tail = null; numMerges = 0; while ( p ) { numMerges ++; q = p; pSize = 0; for ( i = 0; i < inSize; i ++ ) { pSize ++; q = q.nextZ; if ( ! q ) { break; } } qSize = inSize; while ( pSize > 0 || ( qSize > 0 && q ) ) { if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) { e = p; p = p.nextZ; pSize --; } else { e = q; q = q.nextZ; qSize --; } if ( tail ) { tail.nextZ = e; } else { list = e; } e.prevZ = tail; tail = e; } p = q; } tail.nextZ = null; inSize *= 2; } while ( numMerges > 1 ); return list; } // z-order of a point given coords and inverse of the longer side of data bbox function zOrder( x, y, minX, minY, invSize ) { // coords are transformed into non-negative 15-bit integer range x = 32767 * ( x - minX ) * invSize; y = 32767 * ( y - minY ) * invSize; x = ( x | ( x << 8 ) ) & 0x00FF00FF; x = ( x | ( x << 4 ) ) & 0x0F0F0F0F; x = ( x | ( x << 2 ) ) & 0x33333333; x = ( x | ( x << 1 ) ) & 0x55555555; y = ( y | ( y << 8 ) ) & 0x00FF00FF; y = ( y | ( y << 4 ) ) & 0x0F0F0F0F; y = ( y | ( y << 2 ) ) & 0x33333333; y = ( y | ( y << 1 ) ) & 0x55555555; return x | ( y << 1 ); } // find the leftmost node of a polygon ring function getLeftmost( start ) { var p = start, leftmost = start; do { if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) { leftmost = p; } p = p.next; } while ( p !== start ); return leftmost; } // check if a point lies within a convex triangle function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) { return ( cx - px ) * ( ay - py ) - ( ax - px ) * ( cy - py ) >= 0 && ( ax - px ) * ( by - py ) - ( bx - px ) * ( ay - py ) >= 0 && ( bx - px ) * ( cy - py ) - ( cx - px ) * ( by - py ) >= 0; } // check if a diagonal between two polygon nodes is valid (lies in polygon interior) function isValidDiagonal( a, b ) { return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ); } // signed area of a triangle function area( p, q, r ) { return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y ); } // check if two points are equal function equals( p1, p2 ) { return p1.x === p2.x && p1.y === p2.y; } // check if two segments intersect function intersects( p1, q1, p2, q2 ) { if ( ( equals( p1, p2 ) && equals( q1, q2 ) ) || ( equals( p1, q2 ) && equals( p2, q1 ) ) ) { return true; } return area( p1, q1, p2 ) > 0 !== area( p1, q1, q2 ) > 0 && area( p2, q2, p1 ) > 0 !== area( p2, q2, q1 ) > 0; } // check if a polygon diagonal intersects any polygon segments function intersectsPolygon( a, b ) { var p = a; do { if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && intersects( p, p.next, a, b ) ) { return true; } p = p.next; } while ( p !== a ); return false; } // check if a polygon diagonal is locally inside the polygon function locallyInside( a, b ) { return area( a.prev, a, a.next ) < 0 ? area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 : area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0; } // check if the middle point of a polygon diagonal is inside the polygon function middleInside( a, b ) { var p = a, inside = false, px = ( a.x + b.x ) / 2, py = ( a.y + b.y ) / 2; do { if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y && ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) ) { inside = ! inside; } p = p.next; } while ( p !== a ); return inside; } // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two; // if one belongs to the outer ring and another to a hole, it merges it into a single ring function splitPolygon( a, b ) { var a2 = new Node( a.i, a.x, a.y ), b2 = new Node( b.i, b.x, b.y ), an = a.next, bp = b.prev; a.next = b; b.prev = a; a2.next = an; an.prev = a2; b2.next = a2; a2.prev = b2; bp.next = b2; b2.prev = bp; return b2; } // create a node and optionally link it with previous one (in a circular doubly linked list) function insertNode( i, x, y, last ) { var p = new Node( i, x, y ); if ( ! last ) { p.prev = p; p.next = p; } else { p.next = last.next; p.prev = last; last.next.prev = p; last.next = p; } return p; } function removeNode( p ) { p.next.prev = p.prev; p.prev.next = p.next; if ( p.prevZ ) { p.prevZ.nextZ = p.nextZ; } if ( p.nextZ ) { p.nextZ.prevZ = p.prevZ; } } function Node( i, x, y ) { // vertex index in coordinates array this.i = i; // vertex coordinates this.x = x; this.y = y; // previous and next vertex nodes in a polygon ring this.prev = null; this.next = null; // z-order curve value this.z = null; // previous and next nodes in z-order this.prevZ = null; this.nextZ = null; // indicates whether this is a steiner point this.steiner = false; } function signedArea( data, start, end, dim ) { var sum = 0; for ( var i = start, j = end - dim; i < end; i += dim ) { sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] ); j = i; } return sum; } /** * @author zz85 / http://www.lab4games.net/zz85/blog */ var ShapeUtils = { // calculate area of the contour polygon area: function ( contour ) { var n = contour.length; var a = 0.0; for ( var p = n - 1, q = 0; q < n; p = q ++ ) { a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y; } return a * 0.5; }, isClockWise: function ( pts ) { return ShapeUtils.area( pts ) < 0; }, triangulateShape: function ( contour, holes ) { var vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ] var holeIndices = []; // array of hole indices var faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ] removeDupEndPts( contour ); addContour( vertices, contour ); // var holeIndex = contour.length; holes.forEach( removeDupEndPts ); for ( var i = 0; i < holes.length; i ++ ) { holeIndices.push( holeIndex ); holeIndex += holes[ i ].length; addContour( vertices, holes[ i ] ); } // var triangles = Earcut.triangulate( vertices, holeIndices ); // for ( var i = 0; i < triangles.length; i += 3 ) { faces.push( triangles.slice( i, i + 3 ) ); } return faces; } }; function removeDupEndPts( points ) { var l = points.length; if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) { points.pop(); } } function addContour( vertices, contour ) { for ( var i = 0; i < contour.length; i ++ ) { vertices.push( contour[ i ].x ); vertices.push( contour[ i ].y ); } } /** * @author zz85 / http://www.lab4games.net/zz85/blog * * Creates extruded geometry from a path shape. * * parameters = { * * curveSegments: , // number of points on the curves * steps: , // number of points for z-side extrusions / used for subdividing segments of extrude spline too * depth: , // Depth to extrude the shape * * bevelEnabled: , // turn on bevel * bevelThickness: , // how deep into the original shape bevel goes * bevelSize: , // how far from shape outline (including bevelOffset) is bevel * bevelOffset: , // how far from shape outline does bevel start * bevelSegments: , // number of bevel layers * * extrudePath: // curve to extrude shape along * * UVGenerator: // object that provides UV generator functions * * } */ // ExtrudeGeometry function ExtrudeGeometry( shapes, options ) { Geometry.call( this ); this.type = 'ExtrudeGeometry'; this.parameters = { shapes: shapes, options: options }; this.fromBufferGeometry( new ExtrudeBufferGeometry( shapes, options ) ); this.mergeVertices(); } ExtrudeGeometry.prototype = Object.create( Geometry.prototype ); ExtrudeGeometry.prototype.constructor = ExtrudeGeometry; ExtrudeGeometry.prototype.toJSON = function () { var data = Geometry.prototype.toJSON.call( this ); var shapes = this.parameters.shapes; var options = this.parameters.options; return toJSON( shapes, options, data ); }; // ExtrudeBufferGeometry function ExtrudeBufferGeometry( shapes, options ) { BufferGeometry.call( this ); this.type = 'ExtrudeBufferGeometry'; this.parameters = { shapes: shapes, options: options }; shapes = Array.isArray( shapes ) ? shapes : [ shapes ]; var scope = this; var verticesArray = []; var uvArray = []; for ( var i = 0, l = shapes.length; i < l; i ++ ) { var shape = shapes[ i ]; addShape( shape ); } // build geometry this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) ); this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) ); this.computeVertexNormals(); // functions function addShape( shape ) { var placeholder = []; // options var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12; var steps = options.steps !== undefined ? options.steps : 1; var depth = options.depth !== undefined ? options.depth : 100; var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; var bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0; var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3; var extrudePath = options.extrudePath; var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator; // deprecated options if ( options.amount !== undefined ) { console.warn( 'THREE.ExtrudeBufferGeometry: amount has been renamed to depth.' ); depth = options.amount; } // var extrudePts, extrudeByPath = false; var splineTube, binormal, normal, position2; if ( extrudePath ) { extrudePts = extrudePath.getSpacedPoints( steps ); extrudeByPath = true; bevelEnabled = false; // bevels not supported for path extrusion // SETUP TNB variables // TODO1 - have a .isClosed in spline? splineTube = extrudePath.computeFrenetFrames( steps, false ); // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length); binormal = new Vector3(); normal = new Vector3(); position2 = new Vector3(); } // Safeguards if bevels are not enabled if ( ! bevelEnabled ) { bevelSegments = 0; bevelThickness = 0; bevelSize = 0; bevelOffset = 0; } // Variables initialization var ahole, h, hl; // looping of holes var shapePoints = shape.extractPoints( curveSegments ); var vertices = shapePoints.shape; var holes = shapePoints.holes; var reverse = ! ShapeUtils.isClockWise( vertices ); if ( reverse ) { vertices = vertices.reverse(); // Maybe we should also check if holes are in the opposite direction, just to be safe ... for ( h = 0, hl = holes.length; h < hl; h ++ ) { ahole = holes[ h ]; if ( ShapeUtils.isClockWise( ahole ) ) { holes[ h ] = ahole.reverse(); } } } var faces = ShapeUtils.triangulateShape( vertices, holes ); /* Vertices */ var contour = vertices; // vertices has all points but contour has only points of circumference for ( h = 0, hl = holes.length; h < hl; h ++ ) { ahole = holes[ h ]; vertices = vertices.concat( ahole ); } function scalePt2( pt, vec, size ) { if ( ! vec ) { console.error( "THREE.ExtrudeGeometry: vec does not exist" ); } return vec.clone().multiplyScalar( size ).add( pt ); } var b, bs, t, z, vert, vlen = vertices.length, face, flen = faces.length; // Find directions for point movement function getBevelVec( inPt, inPrev, inNext ) { // computes for inPt the corresponding point inPt' on a new contour // shifted by 1 unit (length of normalized vector) to the left // if we walk along contour clockwise, this new contour is outside the old one // // inPt' is the intersection of the two lines parallel to the two // adjacent edges of inPt at a distance of 1 unit on the left side. var v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt // good reading for geometry algorithms (here: line-line intersection) // http://geomalgorithms.com/a05-_intersect-1.html var v_prev_x = inPt.x - inPrev.x, v_prev_y = inPt.y - inPrev.y; var v_next_x = inNext.x - inPt.x, v_next_y = inNext.y - inPt.y; var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y ); // check for collinear edges var collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x ); if ( Math.abs( collinear0 ) > Number.EPSILON ) { // not collinear // length of vectors for normalizing var v_prev_len = Math.sqrt( v_prev_lensq ); var v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y ); // shift adjacent points by unit vectors to the left var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len ); var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len ); var ptNextShift_x = ( inNext.x - v_next_y / v_next_len ); var ptNextShift_y = ( inNext.y + v_next_x / v_next_len ); // scaling factor for v_prev to intersection point var sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y - ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) / ( v_prev_x * v_next_y - v_prev_y * v_next_x ); // vector from inPt to intersection point v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x ); v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y ); // Don't normalize!, otherwise sharp corners become ugly // but prevent crazy spikes var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y ); if ( v_trans_lensq <= 2 ) { return new Vector2( v_trans_x, v_trans_y ); } else { shrink_by = Math.sqrt( v_trans_lensq / 2 ); } } else { // handle special case of collinear edges var direction_eq = false; // assumes: opposite if ( v_prev_x > Number.EPSILON ) { if ( v_next_x > Number.EPSILON ) { direction_eq = true; } } else { if ( v_prev_x < - Number.EPSILON ) { if ( v_next_x < - Number.EPSILON ) { direction_eq = true; } } else { if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) { direction_eq = true; } } } if ( direction_eq ) { // console.log("Warning: lines are a straight sequence"); v_trans_x = - v_prev_y; v_trans_y = v_prev_x; shrink_by = Math.sqrt( v_prev_lensq ); } else { // console.log("Warning: lines are a straight spike"); v_trans_x = v_prev_x; v_trans_y = v_prev_y; shrink_by = Math.sqrt( v_prev_lensq / 2 ); } } return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by ); } var contourMovements = []; for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) { if ( j === il ) { j = 0; } if ( k === il ) { k = 0; } // (j)---(i)---(k) // console.log('i,j,k', i, j , k) contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] ); } var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat(); for ( h = 0, hl = holes.length; h < hl; h ++ ) { ahole = holes[ h ]; oneHoleMovements = []; for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) { if ( j === il ) { j = 0; } if ( k === il ) { k = 0; } // (j)---(i)---(k) oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] ); } holesMovements.push( oneHoleMovements ); verticesMovements = verticesMovements.concat( oneHoleMovements ); } // Loop bevelSegments, 1 for the front, 1 for the back for ( b = 0; b < bevelSegments; b ++ ) { //for ( b = bevelSegments; b > 0; b -- ) { t = b / bevelSegments; z = bevelThickness * Math.cos( t * Math.PI / 2 ); bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset; // contract shape for ( i = 0, il = contour.length; i < il; i ++ ) { vert = scalePt2( contour[ i ], contourMovements[ i ], bs ); v( vert.x, vert.y, - z ); } // expand holes for ( h = 0, hl = holes.length; h < hl; h ++ ) { ahole = holes[ h ]; oneHoleMovements = holesMovements[ h ]; for ( i = 0, il = ahole.length; i < il; i ++ ) { vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs ); v( vert.x, vert.y, - z ); } } } bs = bevelSize + bevelOffset; // Back facing vertices for ( i = 0; i < vlen; i ++ ) { vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ]; if ( ! extrudeByPath ) { v( vert.x, vert.y, 0 ); } else { // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x ); normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x ); binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y ); position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal ); v( position2.x, position2.y, position2.z ); } } // Add stepped vertices... // Including front facing vertices var s; for ( s = 1; s <= steps; s ++ ) { for ( i = 0; i < vlen; i ++ ) { vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ]; if ( ! extrudeByPath ) { v( vert.x, vert.y, depth / steps * s ); } else { // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x ); normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x ); binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y ); position2.copy( extrudePts[ s ] ).add( normal ).add( binormal ); v( position2.x, position2.y, position2.z ); } } } // Add bevel segments planes //for ( b = 1; b <= bevelSegments; b ++ ) { for ( b = bevelSegments - 1; b >= 0; b -- ) { t = b / bevelSegments; z = bevelThickness * Math.cos( t * Math.PI / 2 ); bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset; // contract shape for ( i = 0, il = contour.length; i < il; i ++ ) { vert = scalePt2( contour[ i ], contourMovements[ i ], bs ); v( vert.x, vert.y, depth + z ); } // expand holes for ( h = 0, hl = holes.length; h < hl; h ++ ) { ahole = holes[ h ]; oneHoleMovements = holesMovements[ h ]; for ( i = 0, il = ahole.length; i < il; i ++ ) { vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs ); if ( ! extrudeByPath ) { v( vert.x, vert.y, depth + z ); } else { v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z ); } } } } /* Faces */ // Top and bottom faces buildLidFaces(); // Sides faces buildSideFaces(); ///// Internal functions function buildLidFaces() { var start = verticesArray.length / 3; if ( bevelEnabled ) { var layer = 0; // steps + 1 var offset = vlen * layer; // Bottom faces for ( i = 0; i < flen; i ++ ) { face = faces[ i ]; f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset ); } layer = steps + bevelSegments * 2; offset = vlen * layer; // Top faces for ( i = 0; i < flen; i ++ ) { face = faces[ i ]; f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset ); } } else { // Bottom faces for ( i = 0; i < flen; i ++ ) { face = faces[ i ]; f3( face[ 2 ], face[ 1 ], face[ 0 ] ); } // Top faces for ( i = 0; i < flen; i ++ ) { face = faces[ i ]; f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps ); } } scope.addGroup( start, verticesArray.length / 3 - start, 0 ); } // Create faces for the z-sides of the shape function buildSideFaces() { var start = verticesArray.length / 3; var layeroffset = 0; sidewalls( contour, layeroffset ); layeroffset += contour.length; for ( h = 0, hl = holes.length; h < hl; h ++ ) { ahole = holes[ h ]; sidewalls( ahole, layeroffset ); //, true layeroffset += ahole.length; } scope.addGroup( start, verticesArray.length / 3 - start, 1 ); } function sidewalls( contour, layeroffset ) { var j, k; i = contour.length; while ( -- i >= 0 ) { j = i; k = i - 1; if ( k < 0 ) { k = contour.length - 1; } //console.log('b', i,j, i-1, k,vertices.length); var s = 0, sl = steps + bevelSegments * 2; for ( s = 0; s < sl; s ++ ) { var slen1 = vlen * s; var slen2 = vlen * ( s + 1 ); var a = layeroffset + j + slen1, b = layeroffset + k + slen1, c = layeroffset + k + slen2, d = layeroffset + j + slen2; f4( a, b, c, d ); } } } function v( x, y, z ) { placeholder.push( x ); placeholder.push( y ); placeholder.push( z ); } function f3( a, b, c ) { addVertex( a ); addVertex( b ); addVertex( c ); var nextIndex = verticesArray.length / 3; var uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 ); addUV( uvs[ 0 ] ); addUV( uvs[ 1 ] ); addUV( uvs[ 2 ] ); } function f4( a, b, c, d ) { addVertex( a ); addVertex( b ); addVertex( d ); addVertex( b ); addVertex( c ); addVertex( d ); var nextIndex = verticesArray.length / 3; var uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 ); addUV( uvs[ 0 ] ); addUV( uvs[ 1 ] ); addUV( uvs[ 3 ] ); addUV( uvs[ 1 ] ); addUV( uvs[ 2 ] ); addUV( uvs[ 3 ] ); } function addVertex( index ) { verticesArray.push( placeholder[ index * 3 + 0 ] ); verticesArray.push( placeholder[ index * 3 + 1 ] ); verticesArray.push( placeholder[ index * 3 + 2 ] ); } function addUV( vector2 ) { uvArray.push( vector2.x ); uvArray.push( vector2.y ); } } } ExtrudeBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); ExtrudeBufferGeometry.prototype.constructor = ExtrudeBufferGeometry; ExtrudeBufferGeometry.prototype.toJSON = function () { var data = BufferGeometry.prototype.toJSON.call( this ); var shapes = this.parameters.shapes; var options = this.parameters.options; return toJSON( shapes, options, data ); }; // var WorldUVGenerator = { generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) { var a_x = vertices[ indexA * 3 ]; var a_y = vertices[ indexA * 3 + 1 ]; var b_x = vertices[ indexB * 3 ]; var b_y = vertices[ indexB * 3 + 1 ]; var c_x = vertices[ indexC * 3 ]; var c_y = vertices[ indexC * 3 + 1 ]; return [ new Vector2( a_x, a_y ), new Vector2( b_x, b_y ), new Vector2( c_x, c_y ) ]; }, generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) { var a_x = vertices[ indexA * 3 ]; var a_y = vertices[ indexA * 3 + 1 ]; var a_z = vertices[ indexA * 3 + 2 ]; var b_x = vertices[ indexB * 3 ]; var b_y = vertices[ indexB * 3 + 1 ]; var b_z = vertices[ indexB * 3 + 2 ]; var c_x = vertices[ indexC * 3 ]; var c_y = vertices[ indexC * 3 + 1 ]; var c_z = vertices[ indexC * 3 + 2 ]; var d_x = vertices[ indexD * 3 ]; var d_y = vertices[ indexD * 3 + 1 ]; var d_z = vertices[ indexD * 3 + 2 ]; if ( Math.abs( a_y - b_y ) < 0.01 ) { return [ new Vector2( a_x, 1 - a_z ), new Vector2( b_x, 1 - b_z ), new Vector2( c_x, 1 - c_z ), new Vector2( d_x, 1 - d_z ) ]; } else { return [ new Vector2( a_y, 1 - a_z ), new Vector2( b_y, 1 - b_z ), new Vector2( c_y, 1 - c_z ), new Vector2( d_y, 1 - d_z ) ]; } } }; function toJSON( shapes, options, data ) { // data.shapes = []; if ( Array.isArray( shapes ) ) { for ( var i = 0, l = shapes.length; i < l; i ++ ) { var shape = shapes[ i ]; data.shapes.push( shape.uuid ); } } else { data.shapes.push( shapes.uuid ); } // if ( options.extrudePath !== undefined ) { data.options.extrudePath = options.extrudePath.toJSON(); } return data; } /** * @author zz85 / http://www.lab4games.net/zz85/blog * @author alteredq / http://alteredqualia.com/ * * Text = 3D Text * * parameters = { * font: , // font * * size: , // size of the text * height: , // thickness to extrude text * curveSegments: , // number of points on the curves * * bevelEnabled: , // turn on bevel * bevelThickness: , // how deep into text bevel goes * bevelSize: , // how far from text outline (including bevelOffset) is bevel * bevelOffset: // how far from text outline does bevel start * } */ // TextGeometry function TextGeometry( text, parameters ) { Geometry.call( this ); this.type = 'TextGeometry'; this.parameters = { text: text, parameters: parameters }; this.fromBufferGeometry( new TextBufferGeometry( text, parameters ) ); this.mergeVertices(); } TextGeometry.prototype = Object.create( Geometry.prototype ); TextGeometry.prototype.constructor = TextGeometry; // TextBufferGeometry function TextBufferGeometry( text, parameters ) { parameters = parameters || {}; var font = parameters.font; if ( ! ( font && font.isFont ) ) { console.error( 'THREE.TextGeometry: font parameter is not an instance of THREE.Font.' ); return new Geometry(); } var shapes = font.generateShapes( text, parameters.size ); // translate parameters to ExtrudeGeometry API parameters.depth = parameters.height !== undefined ? parameters.height : 50; // defaults if ( parameters.bevelThickness === undefined ) { parameters.bevelThickness = 10; } if ( parameters.bevelSize === undefined ) { parameters.bevelSize = 8; } if ( parameters.bevelEnabled === undefined ) { parameters.bevelEnabled = false; } ExtrudeBufferGeometry.call( this, shapes, parameters ); this.type = 'TextBufferGeometry'; } TextBufferGeometry.prototype = Object.create( ExtrudeBufferGeometry.prototype ); TextBufferGeometry.prototype.constructor = TextBufferGeometry; /** * @author mrdoob / http://mrdoob.com/ * @author benaadams / https://twitter.com/ben_a_adams * @author Mugen87 / https://github.com/Mugen87 */ // SphereGeometry function SphereGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) { Geometry.call( this ); this.type = 'SphereGeometry'; this.parameters = { radius: radius, widthSegments: widthSegments, heightSegments: heightSegments, phiStart: phiStart, phiLength: phiLength, thetaStart: thetaStart, thetaLength: thetaLength }; this.fromBufferGeometry( new SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) ); this.mergeVertices(); } SphereGeometry.prototype = Object.create( Geometry.prototype ); SphereGeometry.prototype.constructor = SphereGeometry; // SphereBufferGeometry function SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) { BufferGeometry.call( this ); this.type = 'SphereBufferGeometry'; this.parameters = { radius: radius, widthSegments: widthSegments, heightSegments: heightSegments, phiStart: phiStart, phiLength: phiLength, thetaStart: thetaStart, thetaLength: thetaLength }; radius = radius || 1; widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 ); heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 ); phiStart = phiStart !== undefined ? phiStart : 0; phiLength = phiLength !== undefined ? phiLength : Math.PI * 2; thetaStart = thetaStart !== undefined ? thetaStart : 0; thetaLength = thetaLength !== undefined ? thetaLength : Math.PI; var thetaEnd = Math.min( thetaStart + thetaLength, Math.PI ); var ix, iy; var index = 0; var grid = []; var vertex = new Vector3(); var normal = new Vector3(); // buffers var indices = []; var vertices = []; var normals = []; var uvs = []; // generate vertices, normals and uvs for ( iy = 0; iy <= heightSegments; iy ++ ) { var verticesRow = []; var v = iy / heightSegments; // special case for the poles var uOffset = 0; if ( iy == 0 && thetaStart == 0 ) { uOffset = 0.5 / widthSegments; } else if ( iy == heightSegments && thetaEnd == Math.PI ) { uOffset = - 0.5 / widthSegments; } for ( ix = 0; ix <= widthSegments; ix ++ ) { var u = ix / widthSegments; // vertex vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength ); vertex.y = radius * Math.cos( thetaStart + v * thetaLength ); vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength ); vertices.push( vertex.x, vertex.y, vertex.z ); // normal normal.copy( vertex ).normalize(); normals.push( normal.x, normal.y, normal.z ); // uv uvs.push( u + uOffset, 1 - v ); verticesRow.push( index ++ ); } grid.push( verticesRow ); } // indices for ( iy = 0; iy < heightSegments; iy ++ ) { for ( ix = 0; ix < widthSegments; ix ++ ) { var a = grid[ iy ][ ix + 1 ]; var b = grid[ iy ][ ix ]; var c = grid[ iy + 1 ][ ix ]; var d = grid[ iy + 1 ][ ix + 1 ]; if ( iy !== 0 || thetaStart > 0 ) { indices.push( a, b, d ); } if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) { indices.push( b, c, d ); } } } // build geometry this.setIndex( indices ); this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); } SphereBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); SphereBufferGeometry.prototype.constructor = SphereBufferGeometry; /** * @author Kaleb Murphy * @author Mugen87 / https://github.com/Mugen87 */ // RingGeometry function RingGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) { Geometry.call( this ); this.type = 'RingGeometry'; this.parameters = { innerRadius: innerRadius, outerRadius: outerRadius, thetaSegments: thetaSegments, phiSegments: phiSegments, thetaStart: thetaStart, thetaLength: thetaLength }; this.fromBufferGeometry( new RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) ); this.mergeVertices(); } RingGeometry.prototype = Object.create( Geometry.prototype ); RingGeometry.prototype.constructor = RingGeometry; // RingBufferGeometry function RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) { BufferGeometry.call( this ); this.type = 'RingBufferGeometry'; this.parameters = { innerRadius: innerRadius, outerRadius: outerRadius, thetaSegments: thetaSegments, phiSegments: phiSegments, thetaStart: thetaStart, thetaLength: thetaLength }; innerRadius = innerRadius || 0.5; outerRadius = outerRadius || 1; thetaStart = thetaStart !== undefined ? thetaStart : 0; thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2; thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8; phiSegments = phiSegments !== undefined ? Math.max( 1, phiSegments ) : 1; // buffers var indices = []; var vertices = []; var normals = []; var uvs = []; // some helper variables var segment; var radius = innerRadius; var radiusStep = ( ( outerRadius - innerRadius ) / phiSegments ); var vertex = new Vector3(); var uv = new Vector2(); var j, i; // generate vertices, normals and uvs for ( j = 0; j <= phiSegments; j ++ ) { for ( i = 0; i <= thetaSegments; i ++ ) { // values are generate from the inside of the ring to the outside segment = thetaStart + i / thetaSegments * thetaLength; // vertex vertex.x = radius * Math.cos( segment ); vertex.y = radius * Math.sin( segment ); vertices.push( vertex.x, vertex.y, vertex.z ); // normal normals.push( 0, 0, 1 ); // uv uv.x = ( vertex.x / outerRadius + 1 ) / 2; uv.y = ( vertex.y / outerRadius + 1 ) / 2; uvs.push( uv.x, uv.y ); } // increase the radius for next row of vertices radius += radiusStep; } // indices for ( j = 0; j < phiSegments; j ++ ) { var thetaSegmentLevel = j * ( thetaSegments + 1 ); for ( i = 0; i < thetaSegments; i ++ ) { segment = i + thetaSegmentLevel; var a = segment; var b = segment + thetaSegments + 1; var c = segment + thetaSegments + 2; var d = segment + 1; // faces indices.push( a, b, d ); indices.push( b, c, d ); } } // build geometry this.setIndex( indices ); this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); } RingBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); RingBufferGeometry.prototype.constructor = RingBufferGeometry; /** * @author zz85 / https://github.com/zz85 * @author bhouston / http://clara.io * @author Mugen87 / https://github.com/Mugen87 */ // LatheGeometry function LatheGeometry( points, segments, phiStart, phiLength ) { Geometry.call( this ); this.type = 'LatheGeometry'; this.parameters = { points: points, segments: segments, phiStart: phiStart, phiLength: phiLength }; this.fromBufferGeometry( new LatheBufferGeometry( points, segments, phiStart, phiLength ) ); this.mergeVertices(); } LatheGeometry.prototype = Object.create( Geometry.prototype ); LatheGeometry.prototype.constructor = LatheGeometry; // LatheBufferGeometry function LatheBufferGeometry( points, segments, phiStart, phiLength ) { BufferGeometry.call( this ); this.type = 'LatheBufferGeometry'; this.parameters = { points: points, segments: segments, phiStart: phiStart, phiLength: phiLength }; segments = Math.floor( segments ) || 12; phiStart = phiStart || 0; phiLength = phiLength || Math.PI * 2; // clamp phiLength so it's in range of [ 0, 2PI ] phiLength = MathUtils.clamp( phiLength, 0, Math.PI * 2 ); // buffers var indices = []; var vertices = []; var uvs = []; // helper variables var base; var inverseSegments = 1.0 / segments; var vertex = new Vector3(); var uv = new Vector2(); var i, j; // generate vertices and uvs for ( i = 0; i <= segments; i ++ ) { var phi = phiStart + i * inverseSegments * phiLength; var sin = Math.sin( phi ); var cos = Math.cos( phi ); for ( j = 0; j <= ( points.length - 1 ); j ++ ) { // vertex vertex.x = points[ j ].x * sin; vertex.y = points[ j ].y; vertex.z = points[ j ].x * cos; vertices.push( vertex.x, vertex.y, vertex.z ); // uv uv.x = i / segments; uv.y = j / ( points.length - 1 ); uvs.push( uv.x, uv.y ); } } // indices for ( i = 0; i < segments; i ++ ) { for ( j = 0; j < ( points.length - 1 ); j ++ ) { base = j + i * points.length; var a = base; var b = base + points.length; var c = base + points.length + 1; var d = base + 1; // faces indices.push( a, b, d ); indices.push( b, c, d ); } } // build geometry this.setIndex( indices ); this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); // generate normals this.computeVertexNormals(); // if the geometry is closed, we need to average the normals along the seam. // because the corresponding vertices are identical (but still have different UVs). if ( phiLength === Math.PI * 2 ) { var normals = this.attributes.normal.array; var n1 = new Vector3(); var n2 = new Vector3(); var n = new Vector3(); // this is the buffer offset for the last line of vertices base = segments * points.length * 3; for ( i = 0, j = 0; i < points.length; i ++, j += 3 ) { // select the normal of the vertex in the first line n1.x = normals[ j + 0 ]; n1.y = normals[ j + 1 ]; n1.z = normals[ j + 2 ]; // select the normal of the vertex in the last line n2.x = normals[ base + j + 0 ]; n2.y = normals[ base + j + 1 ]; n2.z = normals[ base + j + 2 ]; // average normals n.addVectors( n1, n2 ).normalize(); // assign the new values to both normals normals[ j + 0 ] = normals[ base + j + 0 ] = n.x; normals[ j + 1 ] = normals[ base + j + 1 ] = n.y; normals[ j + 2 ] = normals[ base + j + 2 ] = n.z; } } } LatheBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); LatheBufferGeometry.prototype.constructor = LatheBufferGeometry; /** * @author jonobr1 / http://jonobr1.com * @author Mugen87 / https://github.com/Mugen87 */ // ShapeGeometry function ShapeGeometry( shapes, curveSegments ) { Geometry.call( this ); this.type = 'ShapeGeometry'; if ( typeof curveSegments === 'object' ) { console.warn( 'THREE.ShapeGeometry: Options parameter has been removed.' ); curveSegments = curveSegments.curveSegments; } this.parameters = { shapes: shapes, curveSegments: curveSegments }; this.fromBufferGeometry( new ShapeBufferGeometry( shapes, curveSegments ) ); this.mergeVertices(); } ShapeGeometry.prototype = Object.create( Geometry.prototype ); ShapeGeometry.prototype.constructor = ShapeGeometry; ShapeGeometry.prototype.toJSON = function () { var data = Geometry.prototype.toJSON.call( this ); var shapes = this.parameters.shapes; return toJSON$1( shapes, data ); }; // ShapeBufferGeometry function ShapeBufferGeometry( shapes, curveSegments ) { BufferGeometry.call( this ); this.type = 'ShapeBufferGeometry'; this.parameters = { shapes: shapes, curveSegments: curveSegments }; curveSegments = curveSegments || 12; // buffers var indices = []; var vertices = []; var normals = []; var uvs = []; // helper variables var groupStart = 0; var groupCount = 0; // allow single and array values for "shapes" parameter if ( Array.isArray( shapes ) === false ) { addShape( shapes ); } else { for ( var i = 0; i < shapes.length; i ++ ) { addShape( shapes[ i ] ); this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support groupStart += groupCount; groupCount = 0; } } // build geometry this.setIndex( indices ); this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); // helper functions function addShape( shape ) { var i, l, shapeHole; var indexOffset = vertices.length / 3; var points = shape.extractPoints( curveSegments ); var shapeVertices = points.shape; var shapeHoles = points.holes; // check direction of vertices if ( ShapeUtils.isClockWise( shapeVertices ) === false ) { shapeVertices = shapeVertices.reverse(); } for ( i = 0, l = shapeHoles.length; i < l; i ++ ) { shapeHole = shapeHoles[ i ]; if ( ShapeUtils.isClockWise( shapeHole ) === true ) { shapeHoles[ i ] = shapeHole.reverse(); } } var faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles ); // join vertices of inner and outer paths to a single array for ( i = 0, l = shapeHoles.length; i < l; i ++ ) { shapeHole = shapeHoles[ i ]; shapeVertices = shapeVertices.concat( shapeHole ); } // vertices, normals, uvs for ( i = 0, l = shapeVertices.length; i < l; i ++ ) { var vertex = shapeVertices[ i ]; vertices.push( vertex.x, vertex.y, 0 ); normals.push( 0, 0, 1 ); uvs.push( vertex.x, vertex.y ); // world uvs } // incides for ( i = 0, l = faces.length; i < l; i ++ ) { var face = faces[ i ]; var a = face[ 0 ] + indexOffset; var b = face[ 1 ] + indexOffset; var c = face[ 2 ] + indexOffset; indices.push( a, b, c ); groupCount += 3; } } } ShapeBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); ShapeBufferGeometry.prototype.constructor = ShapeBufferGeometry; ShapeBufferGeometry.prototype.toJSON = function () { var data = BufferGeometry.prototype.toJSON.call( this ); var shapes = this.parameters.shapes; return toJSON$1( shapes, data ); }; // function toJSON$1( shapes, data ) { data.shapes = []; if ( Array.isArray( shapes ) ) { for ( var i = 0, l = shapes.length; i < l; i ++ ) { var shape = shapes[ i ]; data.shapes.push( shape.uuid ); } } else { data.shapes.push( shapes.uuid ); } return data; } /** * @author WestLangley / http://github.com/WestLangley * @author Mugen87 / https://github.com/Mugen87 */ function EdgesGeometry( geometry, thresholdAngle ) { BufferGeometry.call( this ); this.type = 'EdgesGeometry'; this.parameters = { thresholdAngle: thresholdAngle }; thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1; // buffer var vertices = []; // helper variables var thresholdDot = Math.cos( MathUtils.DEG2RAD * thresholdAngle ); var edge = [ 0, 0 ], edges = {}, edge1, edge2; var key, keys = [ 'a', 'b', 'c' ]; // prepare source geometry var geometry2; if ( geometry.isBufferGeometry ) { geometry2 = new Geometry(); geometry2.fromBufferGeometry( geometry ); } else { geometry2 = geometry.clone(); } geometry2.mergeVertices(); geometry2.computeFaceNormals(); var sourceVertices = geometry2.vertices; var faces = geometry2.faces; // now create a data structure where each entry represents an edge with its adjoining faces for ( var i = 0, l = faces.length; i < l; i ++ ) { var face = faces[ i ]; for ( var j = 0; j < 3; j ++ ) { edge1 = face[ keys[ j ] ]; edge2 = face[ keys[ ( j + 1 ) % 3 ] ]; edge[ 0 ] = Math.min( edge1, edge2 ); edge[ 1 ] = Math.max( edge1, edge2 ); key = edge[ 0 ] + ',' + edge[ 1 ]; if ( edges[ key ] === undefined ) { edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ], face1: i, face2: undefined }; } else { edges[ key ].face2 = i; } } } // generate vertices for ( key in edges ) { var e = edges[ key ]; // an edge is only rendered if the angle (in degrees) between the face normals of the adjoining faces exceeds this value. default = 1 degree. if ( e.face2 === undefined || faces[ e.face1 ].normal.dot( faces[ e.face2 ].normal ) <= thresholdDot ) { var vertex = sourceVertices[ e.index1 ]; vertices.push( vertex.x, vertex.y, vertex.z ); vertex = sourceVertices[ e.index2 ]; vertices.push( vertex.x, vertex.y, vertex.z ); } } // build geometry this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); } EdgesGeometry.prototype = Object.create( BufferGeometry.prototype ); EdgesGeometry.prototype.constructor = EdgesGeometry; /** * @author mrdoob / http://mrdoob.com/ * @author Mugen87 / https://github.com/Mugen87 */ // CylinderGeometry function CylinderGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) { Geometry.call( this ); this.type = 'CylinderGeometry'; this.parameters = { radiusTop: radiusTop, radiusBottom: radiusBottom, height: height, radialSegments: radialSegments, heightSegments: heightSegments, openEnded: openEnded, thetaStart: thetaStart, thetaLength: thetaLength }; this.fromBufferGeometry( new CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) ); this.mergeVertices(); } CylinderGeometry.prototype = Object.create( Geometry.prototype ); CylinderGeometry.prototype.constructor = CylinderGeometry; // CylinderBufferGeometry function CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) { BufferGeometry.call( this ); this.type = 'CylinderBufferGeometry'; this.parameters = { radiusTop: radiusTop, radiusBottom: radiusBottom, height: height, radialSegments: radialSegments, heightSegments: heightSegments, openEnded: openEnded, thetaStart: thetaStart, thetaLength: thetaLength }; var scope = this; radiusTop = radiusTop !== undefined ? radiusTop : 1; radiusBottom = radiusBottom !== undefined ? radiusBottom : 1; height = height || 1; radialSegments = Math.floor( radialSegments ) || 8; heightSegments = Math.floor( heightSegments ) || 1; openEnded = openEnded !== undefined ? openEnded : false; thetaStart = thetaStart !== undefined ? thetaStart : 0.0; thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2; // buffers var indices = []; var vertices = []; var normals = []; var uvs = []; // helper variables var index = 0; var indexArray = []; var halfHeight = height / 2; var groupStart = 0; // generate geometry generateTorso(); if ( openEnded === false ) { if ( radiusTop > 0 ) { generateCap( true ); } if ( radiusBottom > 0 ) { generateCap( false ); } } // build geometry this.setIndex( indices ); this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); function generateTorso() { var x, y; var normal = new Vector3(); var vertex = new Vector3(); var groupCount = 0; // this will be used to calculate the normal var slope = ( radiusBottom - radiusTop ) / height; // generate vertices, normals and uvs for ( y = 0; y <= heightSegments; y ++ ) { var indexRow = []; var v = y / heightSegments; // calculate the radius of the current row var radius = v * ( radiusBottom - radiusTop ) + radiusTop; for ( x = 0; x <= radialSegments; x ++ ) { var u = x / radialSegments; var theta = u * thetaLength + thetaStart; var sinTheta = Math.sin( theta ); var cosTheta = Math.cos( theta ); // vertex vertex.x = radius * sinTheta; vertex.y = - v * height + halfHeight; vertex.z = radius * cosTheta; vertices.push( vertex.x, vertex.y, vertex.z ); // normal normal.set( sinTheta, slope, cosTheta ).normalize(); normals.push( normal.x, normal.y, normal.z ); // uv uvs.push( u, 1 - v ); // save index of vertex in respective row indexRow.push( index ++ ); } // now save vertices of the row in our index array indexArray.push( indexRow ); } // generate indices for ( x = 0; x < radialSegments; x ++ ) { for ( y = 0; y < heightSegments; y ++ ) { // we use the index array to access the correct indices var a = indexArray[ y ][ x ]; var b = indexArray[ y + 1 ][ x ]; var c = indexArray[ y + 1 ][ x + 1 ]; var d = indexArray[ y ][ x + 1 ]; // faces indices.push( a, b, d ); indices.push( b, c, d ); // update group counter groupCount += 6; } } // add a group to the geometry. this will ensure multi material support scope.addGroup( groupStart, groupCount, 0 ); // calculate new start value for groups groupStart += groupCount; } function generateCap( top ) { var x, centerIndexStart, centerIndexEnd; var uv = new Vector2(); var vertex = new Vector3(); var groupCount = 0; var radius = ( top === true ) ? radiusTop : radiusBottom; var sign = ( top === true ) ? 1 : - 1; // save the index of the first center vertex centerIndexStart = index; // first we generate the center vertex data of the cap. // because the geometry needs one set of uvs per face, // we must generate a center vertex per face/segment for ( x = 1; x <= radialSegments; x ++ ) { // vertex vertices.push( 0, halfHeight * sign, 0 ); // normal normals.push( 0, sign, 0 ); // uv uvs.push( 0.5, 0.5 ); // increase index index ++; } // save the index of the last center vertex centerIndexEnd = index; // now we generate the surrounding vertices, normals and uvs for ( x = 0; x <= radialSegments; x ++ ) { var u = x / radialSegments; var theta = u * thetaLength + thetaStart; var cosTheta = Math.cos( theta ); var sinTheta = Math.sin( theta ); // vertex vertex.x = radius * sinTheta; vertex.y = halfHeight * sign; vertex.z = radius * cosTheta; vertices.push( vertex.x, vertex.y, vertex.z ); // normal normals.push( 0, sign, 0 ); // uv uv.x = ( cosTheta * 0.5 ) + 0.5; uv.y = ( sinTheta * 0.5 * sign ) + 0.5; uvs.push( uv.x, uv.y ); // increase index index ++; } // generate indices for ( x = 0; x < radialSegments; x ++ ) { var c = centerIndexStart + x; var i = centerIndexEnd + x; if ( top === true ) { // face top indices.push( i, i + 1, c ); } else { // face bottom indices.push( i + 1, i, c ); } groupCount += 3; } // add a group to the geometry. this will ensure multi material support scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 ); // calculate new start value for groups groupStart += groupCount; } } CylinderBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); CylinderBufferGeometry.prototype.constructor = CylinderBufferGeometry; /** * @author abelnation / http://github.com/abelnation */ // ConeGeometry function ConeGeometry( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) { CylinderGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ); this.type = 'ConeGeometry'; this.parameters = { radius: radius, height: height, radialSegments: radialSegments, heightSegments: heightSegments, openEnded: openEnded, thetaStart: thetaStart, thetaLength: thetaLength }; } ConeGeometry.prototype = Object.create( CylinderGeometry.prototype ); ConeGeometry.prototype.constructor = ConeGeometry; // ConeBufferGeometry function ConeBufferGeometry( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) { CylinderBufferGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ); this.type = 'ConeBufferGeometry'; this.parameters = { radius: radius, height: height, radialSegments: radialSegments, heightSegments: heightSegments, openEnded: openEnded, thetaStart: thetaStart, thetaLength: thetaLength }; } ConeBufferGeometry.prototype = Object.create( CylinderBufferGeometry.prototype ); ConeBufferGeometry.prototype.constructor = ConeBufferGeometry; /** * @author benaadams / https://twitter.com/ben_a_adams * @author Mugen87 / https://github.com/Mugen87 * @author hughes */ // CircleGeometry function CircleGeometry( radius, segments, thetaStart, thetaLength ) { Geometry.call( this ); this.type = 'CircleGeometry'; this.parameters = { radius: radius, segments: segments, thetaStart: thetaStart, thetaLength: thetaLength }; this.fromBufferGeometry( new CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) ); this.mergeVertices(); } CircleGeometry.prototype = Object.create( Geometry.prototype ); CircleGeometry.prototype.constructor = CircleGeometry; // CircleBufferGeometry function CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) { BufferGeometry.call( this ); this.type = 'CircleBufferGeometry'; this.parameters = { radius: radius, segments: segments, thetaStart: thetaStart, thetaLength: thetaLength }; radius = radius || 1; segments = segments !== undefined ? Math.max( 3, segments ) : 8; thetaStart = thetaStart !== undefined ? thetaStart : 0; thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2; // buffers var indices = []; var vertices = []; var normals = []; var uvs = []; // helper variables var i, s; var vertex = new Vector3(); var uv = new Vector2(); // center point vertices.push( 0, 0, 0 ); normals.push( 0, 0, 1 ); uvs.push( 0.5, 0.5 ); for ( s = 0, i = 3; s <= segments; s ++, i += 3 ) { var segment = thetaStart + s / segments * thetaLength; // vertex vertex.x = radius * Math.cos( segment ); vertex.y = radius * Math.sin( segment ); vertices.push( vertex.x, vertex.y, vertex.z ); // normal normals.push( 0, 0, 1 ); // uvs uv.x = ( vertices[ i ] / radius + 1 ) / 2; uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2; uvs.push( uv.x, uv.y ); } // indices for ( i = 1; i <= segments; i ++ ) { indices.push( i, i + 1, 0 ); } // build geometry this.setIndex( indices ); this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); } CircleBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); CircleBufferGeometry.prototype.constructor = CircleBufferGeometry; var Geometries = /*#__PURE__*/Object.freeze({ __proto__: null, WireframeGeometry: WireframeGeometry, ParametricGeometry: ParametricGeometry, ParametricBufferGeometry: ParametricBufferGeometry, TetrahedronGeometry: TetrahedronGeometry, TetrahedronBufferGeometry: TetrahedronBufferGeometry, OctahedronGeometry: OctahedronGeometry, OctahedronBufferGeometry: OctahedronBufferGeometry, IcosahedronGeometry: IcosahedronGeometry, IcosahedronBufferGeometry: IcosahedronBufferGeometry, DodecahedronGeometry: DodecahedronGeometry, DodecahedronBufferGeometry: DodecahedronBufferGeometry, PolyhedronGeometry: PolyhedronGeometry, PolyhedronBufferGeometry: PolyhedronBufferGeometry, TubeGeometry: TubeGeometry, TubeBufferGeometry: TubeBufferGeometry, TorusKnotGeometry: TorusKnotGeometry, TorusKnotBufferGeometry: TorusKnotBufferGeometry, TorusGeometry: TorusGeometry, TorusBufferGeometry: TorusBufferGeometry, TextGeometry: TextGeometry, TextBufferGeometry: TextBufferGeometry, SphereGeometry: SphereGeometry, SphereBufferGeometry: SphereBufferGeometry, RingGeometry: RingGeometry, RingBufferGeometry: RingBufferGeometry, PlaneGeometry: PlaneGeometry, PlaneBufferGeometry: PlaneBufferGeometry, LatheGeometry: LatheGeometry, LatheBufferGeometry: LatheBufferGeometry, ShapeGeometry: ShapeGeometry, ShapeBufferGeometry: ShapeBufferGeometry, ExtrudeGeometry: ExtrudeGeometry, ExtrudeBufferGeometry: ExtrudeBufferGeometry, EdgesGeometry: EdgesGeometry, ConeGeometry: ConeGeometry, ConeBufferGeometry: ConeBufferGeometry, CylinderGeometry: CylinderGeometry, CylinderBufferGeometry: CylinderBufferGeometry, CircleGeometry: CircleGeometry, CircleBufferGeometry: CircleBufferGeometry, BoxGeometry: BoxGeometry, BoxBufferGeometry: BoxBufferGeometry }); /** * @author mrdoob / http://mrdoob.com/ * * parameters = { * color: * } */ function ShadowMaterial( parameters ) { Material.call( this ); this.type = 'ShadowMaterial'; this.color = new Color( 0x000000 ); this.transparent = true; this.setValues( parameters ); } ShadowMaterial.prototype = Object.create( Material.prototype ); ShadowMaterial.prototype.constructor = ShadowMaterial; ShadowMaterial.prototype.isShadowMaterial = true; ShadowMaterial.prototype.copy = function ( source ) { Material.prototype.copy.call( this, source ); this.color.copy( source.color ); return this; }; /** * @author mrdoob / http://mrdoob.com/ */ function RawShaderMaterial( parameters ) { ShaderMaterial.call( this, parameters ); this.type = 'RawShaderMaterial'; } RawShaderMaterial.prototype = Object.create( ShaderMaterial.prototype ); RawShaderMaterial.prototype.constructor = RawShaderMaterial; RawShaderMaterial.prototype.isRawShaderMaterial = true; /** * @author WestLangley / http://github.com/WestLangley * * parameters = { * color: , * roughness: , * metalness: , * opacity: , * * map: new THREE.Texture( ), * * lightMap: new THREE.Texture( ), * lightMapIntensity: * * aoMap: new THREE.Texture( ), * aoMapIntensity: * * emissive: , * emissiveIntensity: * emissiveMap: new THREE.Texture( ), * * bumpMap: new THREE.Texture( ), * bumpScale: , * * normalMap: new THREE.Texture( ), * normalMapType: THREE.TangentSpaceNormalMap, * normalScale: , * * displacementMap: new THREE.Texture( ), * displacementScale: , * displacementBias: , * * roughnessMap: new THREE.Texture( ), * * metalnessMap: new THREE.Texture( ), * * alphaMap: new THREE.Texture( ), * * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ), * envMapIntensity: * * refractionRatio: , * * wireframe: , * wireframeLinewidth: , * * skinning: , * morphTargets: , * morphNormals: * } */ function MeshStandardMaterial( parameters ) { Material.call( this ); this.defines = { 'STANDARD': '' }; this.type = 'MeshStandardMaterial'; this.color = new Color( 0xffffff ); // diffuse this.roughness = 1.0; this.metalness = 0.0; this.map = null; this.lightMap = null; this.lightMapIntensity = 1.0; this.aoMap = null; this.aoMapIntensity = 1.0; this.emissive = new Color( 0x000000 ); this.emissiveIntensity = 1.0; this.emissiveMap = null; this.bumpMap = null; this.bumpScale = 1; this.normalMap = null; this.normalMapType = TangentSpaceNormalMap; this.normalScale = new Vector2( 1, 1 ); this.displacementMap = null; this.displacementScale = 1; this.displacementBias = 0; this.roughnessMap = null; this.metalnessMap = null; this.alphaMap = null; this.envMap = null; this.envMapIntensity = 1.0; this.refractionRatio = 0.98; this.wireframe = false; this.wireframeLinewidth = 1; this.wireframeLinecap = 'round'; this.wireframeLinejoin = 'round'; this.skinning = false; this.morphTargets = false; this.morphNormals = false; this.setValues( parameters ); } MeshStandardMaterial.prototype = Object.create( Material.prototype ); MeshStandardMaterial.prototype.constructor = MeshStandardMaterial; MeshStandardMaterial.prototype.isMeshStandardMaterial = true; MeshStandardMaterial.prototype.copy = function ( source ) { Material.prototype.copy.call( this, source ); this.defines = { 'STANDARD': '' }; this.color.copy( source.color ); this.roughness = source.roughness; this.metalness = source.metalness; this.map = source.map; this.lightMap = source.lightMap; this.lightMapIntensity = source.lightMapIntensity; this.aoMap = source.aoMap; this.aoMapIntensity = source.aoMapIntensity; this.emissive.copy( source.emissive ); this.emissiveMap = source.emissiveMap; this.emissiveIntensity = source.emissiveIntensity; this.bumpMap = source.bumpMap; this.bumpScale = source.bumpScale; this.normalMap = source.normalMap; this.normalMapType = source.normalMapType; this.normalScale.copy( source.normalScale ); this.displacementMap = source.displacementMap; this.displacementScale = source.displacementScale; this.displacementBias = source.displacementBias; this.roughnessMap = source.roughnessMap; this.metalnessMap = source.metalnessMap; this.alphaMap = source.alphaMap; this.envMap = source.envMap; this.envMapIntensity = source.envMapIntensity; this.refractionRatio = source.refractionRatio; this.wireframe = source.wireframe; this.wireframeLinewidth = source.wireframeLinewidth; this.wireframeLinecap = source.wireframeLinecap; this.wireframeLinejoin = source.wireframeLinejoin; this.skinning = source.skinning; this.morphTargets = source.morphTargets; this.morphNormals = source.morphNormals; return this; }; /** * @author WestLangley / http://github.com/WestLangley * * parameters = { * reflectivity: * clearcoat: * clearcoatRoughness: * * sheen: * * clearcoatNormalScale: , * clearcoatNormalMap: new THREE.Texture( ), * } */ function MeshPhysicalMaterial( parameters ) { MeshStandardMaterial.call( this ); this.defines = { 'STANDARD': '', 'PHYSICAL': '' }; this.type = 'MeshPhysicalMaterial'; this.reflectivity = 0.5; // maps to F0 = 0.04 this.clearcoat = 0.0; this.clearcoatRoughness = 0.0; this.sheen = null; // null will disable sheen bsdf this.clearcoatNormalScale = new Vector2( 1, 1 ); this.clearcoatNormalMap = null; this.transparency = 0.0; this.setValues( parameters ); } MeshPhysicalMaterial.prototype = Object.create( MeshStandardMaterial.prototype ); MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial; MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true; MeshPhysicalMaterial.prototype.copy = function ( source ) { MeshStandardMaterial.prototype.copy.call( this, source ); this.defines = { 'STANDARD': '', 'PHYSICAL': '' }; this.reflectivity = source.reflectivity; this.clearcoat = source.clearcoat; this.clearcoatRoughness = source.clearcoatRoughness; if ( source.sheen ) { this.sheen = ( this.sheen || new Color() ).copy( source.sheen ); } else { this.sheen = null; } this.clearcoatNormalMap = source.clearcoatNormalMap; this.clearcoatNormalScale.copy( source.clearcoatNormalScale ); this.transparency = source.transparency; return this; }; /** * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ * * parameters = { * color: , * specular: , * shininess: , * opacity: , * * map: new THREE.Texture( ), * * lightMap: new THREE.Texture( ), * lightMapIntensity: * * aoMap: new THREE.Texture( ), * aoMapIntensity: * * emissive: , * emissiveIntensity: * emissiveMap: new THREE.Texture( ), * * bumpMap: new THREE.Texture( ), * bumpScale: , * * normalMap: new THREE.Texture( ), * normalMapType: THREE.TangentSpaceNormalMap, * normalScale: , * * displacementMap: new THREE.Texture( ), * displacementScale: , * displacementBias: , * * specularMap: new THREE.Texture( ), * * alphaMap: new THREE.Texture( ), * * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ), * combine: THREE.MultiplyOperation, * reflectivity: , * refractionRatio: , * * wireframe: , * wireframeLinewidth: , * * skinning: , * morphTargets: , * morphNormals: * } */ function MeshPhongMaterial( parameters ) { Material.call( this ); this.type = 'MeshPhongMaterial'; this.color = new Color( 0xffffff ); // diffuse this.specular = new Color( 0x111111 ); this.shininess = 30; this.map = null; this.lightMap = null; this.lightMapIntensity = 1.0; this.aoMap = null; this.aoMapIntensity = 1.0; this.emissive = new Color( 0x000000 ); this.emissiveIntensity = 1.0; this.emissiveMap = null; this.bumpMap = null; this.bumpScale = 1; this.normalMap = null; this.normalMapType = TangentSpaceNormalMap; this.normalScale = new Vector2( 1, 1 ); this.displacementMap = null; this.displacementScale = 1; this.displacementBias = 0; this.specularMap = null; this.alphaMap = null; this.envMap = null; this.combine = MultiplyOperation; this.reflectivity = 1; this.refractionRatio = 0.98; this.wireframe = false; this.wireframeLinewidth = 1; this.wireframeLinecap = 'round'; this.wireframeLinejoin = 'round'; this.skinning = false; this.morphTargets = false; this.morphNormals = false; this.setValues( parameters ); } MeshPhongMaterial.prototype = Object.create( Material.prototype ); MeshPhongMaterial.prototype.constructor = MeshPhongMaterial; MeshPhongMaterial.prototype.isMeshPhongMaterial = true; MeshPhongMaterial.prototype.copy = function ( source ) { Material.prototype.copy.call( this, source ); this.color.copy( source.color ); this.specular.copy( source.specular ); this.shininess = source.shininess; this.map = source.map; this.lightMap = source.lightMap; this.lightMapIntensity = source.lightMapIntensity; this.aoMap = source.aoMap; this.aoMapIntensity = source.aoMapIntensity; this.emissive.copy( source.emissive ); this.emissiveMap = source.emissiveMap; this.emissiveIntensity = source.emissiveIntensity; this.bumpMap = source.bumpMap; this.bumpScale = source.bumpScale; this.normalMap = source.normalMap; this.normalMapType = source.normalMapType; this.normalScale.copy( source.normalScale ); this.displacementMap = source.displacementMap; this.displacementScale = source.displacementScale; this.displacementBias = source.displacementBias; this.specularMap = source.specularMap; this.alphaMap = source.alphaMap; this.envMap = source.envMap; this.combine = source.combine; this.reflectivity = source.reflectivity; this.refractionRatio = source.refractionRatio; this.wireframe = source.wireframe; this.wireframeLinewidth = source.wireframeLinewidth; this.wireframeLinecap = source.wireframeLinecap; this.wireframeLinejoin = source.wireframeLinejoin; this.skinning = source.skinning; this.morphTargets = source.morphTargets; this.morphNormals = source.morphNormals; return this; }; /** * @author takahirox / http://github.com/takahirox * * parameters = { * color: , * specular: , * shininess: , * * map: new THREE.Texture( ), * gradientMap: new THREE.Texture( ), * * lightMap: new THREE.Texture( ), * lightMapIntensity: * * aoMap: new THREE.Texture( ), * aoMapIntensity: * * emissive: , * emissiveIntensity: * emissiveMap: new THREE.Texture( ), * * bumpMap: new THREE.Texture( ), * bumpScale: , * * normalMap: new THREE.Texture( ), * normalMapType: THREE.TangentSpaceNormalMap, * normalScale: , * * displacementMap: new THREE.Texture( ), * displacementScale: , * displacementBias: , * * specularMap: new THREE.Texture( ), * * alphaMap: new THREE.Texture( ), * * wireframe: , * wireframeLinewidth: , * * skinning: , * morphTargets: , * morphNormals: * } */ function MeshToonMaterial( parameters ) { Material.call( this ); this.defines = { 'TOON': '' }; this.type = 'MeshToonMaterial'; this.color = new Color( 0xffffff ); this.specular = new Color( 0x111111 ); this.shininess = 30; this.map = null; this.gradientMap = null; this.lightMap = null; this.lightMapIntensity = 1.0; this.aoMap = null; this.aoMapIntensity = 1.0; this.emissive = new Color( 0x000000 ); this.emissiveIntensity = 1.0; this.emissiveMap = null; this.bumpMap = null; this.bumpScale = 1; this.normalMap = null; this.normalMapType = TangentSpaceNormalMap; this.normalScale = new Vector2( 1, 1 ); this.displacementMap = null; this.displacementScale = 1; this.displacementBias = 0; this.specularMap = null; this.alphaMap = null; this.wireframe = false; this.wireframeLinewidth = 1; this.wireframeLinecap = 'round'; this.wireframeLinejoin = 'round'; this.skinning = false; this.morphTargets = false; this.morphNormals = false; this.setValues( parameters ); } MeshToonMaterial.prototype = Object.create( Material.prototype ); MeshToonMaterial.prototype.constructor = MeshToonMaterial; MeshToonMaterial.prototype.isMeshToonMaterial = true; MeshToonMaterial.prototype.copy = function ( source ) { Material.prototype.copy.call( this, source ); this.color.copy( source.color ); this.specular.copy( source.specular ); this.shininess = source.shininess; this.map = source.map; this.gradientMap = source.gradientMap; this.lightMap = source.lightMap; this.lightMapIntensity = source.lightMapIntensity; this.aoMap = source.aoMap; this.aoMapIntensity = source.aoMapIntensity; this.emissive.copy( source.emissive ); this.emissiveMap = source.emissiveMap; this.emissiveIntensity = source.emissiveIntensity; this.bumpMap = source.bumpMap; this.bumpScale = source.bumpScale; this.normalMap = source.normalMap; this.normalMapType = source.normalMapType; this.normalScale.copy( source.normalScale ); this.displacementMap = source.displacementMap; this.displacementScale = source.displacementScale; this.displacementBias = source.displacementBias; this.specularMap = source.specularMap; this.alphaMap = source.alphaMap; this.wireframe = source.wireframe; this.wireframeLinewidth = source.wireframeLinewidth; this.wireframeLinecap = source.wireframeLinecap; this.wireframeLinejoin = source.wireframeLinejoin; this.skinning = source.skinning; this.morphTargets = source.morphTargets; this.morphNormals = source.morphNormals; return this; }; /** * @author mrdoob / http://mrdoob.com/ * @author WestLangley / http://github.com/WestLangley * * parameters = { * opacity: , * * bumpMap: new THREE.Texture( ), * bumpScale: , * * normalMap: new THREE.Texture( ), * normalMapType: THREE.TangentSpaceNormalMap, * normalScale: , * * displacementMap: new THREE.Texture( ), * displacementScale: , * displacementBias: , * * wireframe: , * wireframeLinewidth: * * skinning: , * morphTargets: , * morphNormals: * } */ function MeshNormalMaterial( parameters ) { Material.call( this ); this.type = 'MeshNormalMaterial'; this.bumpMap = null; this.bumpScale = 1; this.normalMap = null; this.normalMapType = TangentSpaceNormalMap; this.normalScale = new Vector2( 1, 1 ); this.displacementMap = null; this.displacementScale = 1; this.displacementBias = 0; this.wireframe = false; this.wireframeLinewidth = 1; this.fog = false; this.skinning = false; this.morphTargets = false; this.morphNormals = false; this.setValues( parameters ); } MeshNormalMaterial.prototype = Object.create( Material.prototype ); MeshNormalMaterial.prototype.constructor = MeshNormalMaterial; MeshNormalMaterial.prototype.isMeshNormalMaterial = true; MeshNormalMaterial.prototype.copy = function ( source ) { Material.prototype.copy.call( this, source ); this.bumpMap = source.bumpMap; this.bumpScale = source.bumpScale; this.normalMap = source.normalMap; this.normalMapType = source.normalMapType; this.normalScale.copy( source.normalScale ); this.displacementMap = source.displacementMap; this.displacementScale = source.displacementScale; this.displacementBias = source.displacementBias; this.wireframe = source.wireframe; this.wireframeLinewidth = source.wireframeLinewidth; this.skinning = source.skinning; this.morphTargets = source.morphTargets; this.morphNormals = source.morphNormals; return this; }; /** * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ * * parameters = { * color: , * opacity: , * * map: new THREE.Texture( ), * * lightMap: new THREE.Texture( ), * lightMapIntensity: * * aoMap: new THREE.Texture( ), * aoMapIntensity: * * emissive: , * emissiveIntensity: * emissiveMap: new THREE.Texture( ), * * specularMap: new THREE.Texture( ), * * alphaMap: new THREE.Texture( ), * * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ), * combine: THREE.Multiply, * reflectivity: , * refractionRatio: , * * wireframe: , * wireframeLinewidth: , * * skinning: , * morphTargets: , * morphNormals: * } */ function MeshLambertMaterial( parameters ) { Material.call( this ); this.type = 'MeshLambertMaterial'; this.color = new Color( 0xffffff ); // diffuse this.map = null; this.lightMap = null; this.lightMapIntensity = 1.0; this.aoMap = null; this.aoMapIntensity = 1.0; this.emissive = new Color( 0x000000 ); this.emissiveIntensity = 1.0; this.emissiveMap = null; this.specularMap = null; this.alphaMap = null; this.envMap = null; this.combine = MultiplyOperation; this.reflectivity = 1; this.refractionRatio = 0.98; this.wireframe = false; this.wireframeLinewidth = 1; this.wireframeLinecap = 'round'; this.wireframeLinejoin = 'round'; this.skinning = false; this.morphTargets = false; this.morphNormals = false; this.setValues( parameters ); } MeshLambertMaterial.prototype = Object.create( Material.prototype ); MeshLambertMaterial.prototype.constructor = MeshLambertMaterial; MeshLambertMaterial.prototype.isMeshLambertMaterial = true; MeshLambertMaterial.prototype.copy = function ( source ) { Material.prototype.copy.call( this, source ); this.color.copy( source.color ); this.map = source.map; this.lightMap = source.lightMap; this.lightMapIntensity = source.lightMapIntensity; this.aoMap = source.aoMap; this.aoMapIntensity = source.aoMapIntensity; this.emissive.copy( source.emissive ); this.emissiveMap = source.emissiveMap; this.emissiveIntensity = source.emissiveIntensity; this.specularMap = source.specularMap; this.alphaMap = source.alphaMap; this.envMap = source.envMap; this.combine = source.combine; this.reflectivity = source.reflectivity; this.refractionRatio = source.refractionRatio; this.wireframe = source.wireframe; this.wireframeLinewidth = source.wireframeLinewidth; this.wireframeLinecap = source.wireframeLinecap; this.wireframeLinejoin = source.wireframeLinejoin; this.skinning = source.skinning; this.morphTargets = source.morphTargets; this.morphNormals = source.morphNormals; return this; }; /** * @author WestLangley / http://github.com/WestLangley * * parameters = { * color: , * opacity: , * * matcap: new THREE.Texture( ), * * map: new THREE.Texture( ), * * bumpMap: new THREE.Texture( ), * bumpScale: , * * normalMap: new THREE.Texture( ), * normalMapType: THREE.TangentSpaceNormalMap, * normalScale: , * * displacementMap: new THREE.Texture( ), * displacementScale: , * displacementBias: , * * alphaMap: new THREE.Texture( ), * * skinning: , * morphTargets: , * morphNormals: * } */ function MeshMatcapMaterial( parameters ) { Material.call( this ); this.defines = { 'MATCAP': '' }; this.type = 'MeshMatcapMaterial'; this.color = new Color( 0xffffff ); // diffuse this.matcap = null; this.map = null; this.bumpMap = null; this.bumpScale = 1; this.normalMap = null; this.normalMapType = TangentSpaceNormalMap; this.normalScale = new Vector2( 1, 1 ); this.displacementMap = null; this.displacementScale = 1; this.displacementBias = 0; this.alphaMap = null; this.skinning = false; this.morphTargets = false; this.morphNormals = false; this.setValues( parameters ); } MeshMatcapMaterial.prototype = Object.create( Material.prototype ); MeshMatcapMaterial.prototype.constructor = MeshMatcapMaterial; MeshMatcapMaterial.prototype.isMeshMatcapMaterial = true; MeshMatcapMaterial.prototype.copy = function ( source ) { Material.prototype.copy.call( this, source ); this.defines = { 'MATCAP': '' }; this.color.copy( source.color ); this.matcap = source.matcap; this.map = source.map; this.bumpMap = source.bumpMap; this.bumpScale = source.bumpScale; this.normalMap = source.normalMap; this.normalMapType = source.normalMapType; this.normalScale.copy( source.normalScale ); this.displacementMap = source.displacementMap; this.displacementScale = source.displacementScale; this.displacementBias = source.displacementBias; this.alphaMap = source.alphaMap; this.skinning = source.skinning; this.morphTargets = source.morphTargets; this.morphNormals = source.morphNormals; return this; }; /** * @author alteredq / http://alteredqualia.com/ * * parameters = { * color: , * opacity: , * * linewidth: , * * scale: , * dashSize: , * gapSize: * } */ function LineDashedMaterial( parameters ) { LineBasicMaterial.call( this ); this.type = 'LineDashedMaterial'; this.scale = 1; this.dashSize = 3; this.gapSize = 1; this.setValues( parameters ); } LineDashedMaterial.prototype = Object.create( LineBasicMaterial.prototype ); LineDashedMaterial.prototype.constructor = LineDashedMaterial; LineDashedMaterial.prototype.isLineDashedMaterial = true; LineDashedMaterial.prototype.copy = function ( source ) { LineBasicMaterial.prototype.copy.call( this, source ); this.scale = source.scale; this.dashSize = source.dashSize; this.gapSize = source.gapSize; return this; }; var Materials = /*#__PURE__*/Object.freeze({ __proto__: null, ShadowMaterial: ShadowMaterial, SpriteMaterial: SpriteMaterial, RawShaderMaterial: RawShaderMaterial, ShaderMaterial: ShaderMaterial, PointsMaterial: PointsMaterial, MeshPhysicalMaterial: MeshPhysicalMaterial, MeshStandardMaterial: MeshStandardMaterial, MeshPhongMaterial: MeshPhongMaterial, MeshToonMaterial: MeshToonMaterial, MeshNormalMaterial: MeshNormalMaterial, MeshLambertMaterial: MeshLambertMaterial, MeshDepthMaterial: MeshDepthMaterial, MeshDistanceMaterial: MeshDistanceMaterial, MeshBasicMaterial: MeshBasicMaterial, MeshMatcapMaterial: MeshMatcapMaterial, LineDashedMaterial: LineDashedMaterial, LineBasicMaterial: LineBasicMaterial, Material: Material }); /** * @author tschw * @author Ben Houston / http://clara.io/ * @author David Sarno / http://lighthaus.us/ */ var AnimationUtils = { // same as Array.prototype.slice, but also works on typed arrays arraySlice: function ( array, from, to ) { if ( AnimationUtils.isTypedArray( array ) ) { // in ios9 array.subarray(from, undefined) will return empty array // but array.subarray(from) or array.subarray(from, len) is correct return new array.constructor( array.subarray( from, to !== undefined ? to : array.length ) ); } return array.slice( from, to ); }, // converts an array to a specific type convertArray: function ( array, type, forceClone ) { if ( ! array || // let 'undefined' and 'null' pass ! forceClone && array.constructor === type ) { return array; } if ( typeof type.BYTES_PER_ELEMENT === 'number' ) { return new type( array ); // create typed array } return Array.prototype.slice.call( array ); // create Array }, isTypedArray: function ( object ) { return ArrayBuffer.isView( object ) && ! ( object instanceof DataView ); }, // returns an array by which times and values can be sorted getKeyframeOrder: function ( times ) { function compareTime( i, j ) { return times[ i ] - times[ j ]; } var n = times.length; var result = new Array( n ); for ( var i = 0; i !== n; ++ i ) { result[ i ] = i; } result.sort( compareTime ); return result; }, // uses the array previously returned by 'getKeyframeOrder' to sort data sortedArray: function ( values, stride, order ) { var nValues = values.length; var result = new values.constructor( nValues ); for ( var i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) { var srcOffset = order[ i ] * stride; for ( var j = 0; j !== stride; ++ j ) { result[ dstOffset ++ ] = values[ srcOffset + j ]; } } return result; }, // function for parsing AOS keyframe formats flattenJSON: function ( jsonKeys, times, values, valuePropertyName ) { var i = 1, key = jsonKeys[ 0 ]; while ( key !== undefined && key[ valuePropertyName ] === undefined ) { key = jsonKeys[ i ++ ]; } if ( key === undefined ) { return; } // no data var value = key[ valuePropertyName ]; if ( value === undefined ) { return; } // no data if ( Array.isArray( value ) ) { do { value = key[ valuePropertyName ]; if ( value !== undefined ) { times.push( key.time ); values.push.apply( values, value ); // push all elements } key = jsonKeys[ i ++ ]; } while ( key !== undefined ); } else if ( value.toArray !== undefined ) { // ...assume THREE.Math-ish do { value = key[ valuePropertyName ]; if ( value !== undefined ) { times.push( key.time ); value.toArray( values, values.length ); } key = jsonKeys[ i ++ ]; } while ( key !== undefined ); } else { // otherwise push as-is do { value = key[ valuePropertyName ]; if ( value !== undefined ) { times.push( key.time ); values.push( value ); } key = jsonKeys[ i ++ ]; } while ( key !== undefined ); } }, subclip: function ( sourceClip, name, startFrame, endFrame, fps ) { fps = fps || 30; var clip = sourceClip.clone(); clip.name = name; var tracks = []; for ( var i = 0; i < clip.tracks.length; ++ i ) { var track = clip.tracks[ i ]; var valueSize = track.getValueSize(); var times = []; var values = []; for ( var j = 0; j < track.times.length; ++ j ) { var frame = track.times[ j ] * fps; if ( frame < startFrame || frame >= endFrame ) { continue; } times.push( track.times[ j ] ); for ( var k = 0; k < valueSize; ++ k ) { values.push( track.values[ j * valueSize + k ] ); } } if ( times.length === 0 ) { continue; } track.times = AnimationUtils.convertArray( times, track.times.constructor ); track.values = AnimationUtils.convertArray( values, track.values.constructor ); tracks.push( track ); } clip.tracks = tracks; // find minimum .times value across all tracks in the trimmed clip var minStartTime = Infinity; for ( var i = 0; i < clip.tracks.length; ++ i ) { if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) { minStartTime = clip.tracks[ i ].times[ 0 ]; } } // shift all tracks such that clip begins at t=0 for ( var i = 0; i < clip.tracks.length; ++ i ) { clip.tracks[ i ].shift( - 1 * minStartTime ); } clip.resetDuration(); return clip; } }; /** * Abstract base class of interpolants over parametric samples. * * The parameter domain is one dimensional, typically the time or a path * along a curve defined by the data. * * The sample values can have any dimensionality and derived classes may * apply special interpretations to the data. * * This class provides the interval seek in a Template Method, deferring * the actual interpolation to derived classes. * * Time complexity is O(1) for linear access crossing at most two points * and O(log N) for random access, where N is the number of positions. * * References: * * http://www.oodesign.com/template-method-pattern.html * * @author tschw */ function Interpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) { this.parameterPositions = parameterPositions; this._cachedIndex = 0; this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor( sampleSize ); this.sampleValues = sampleValues; this.valueSize = sampleSize; } Object.assign( Interpolant.prototype, { evaluate: function ( t ) { var pp = this.parameterPositions, i1 = this._cachedIndex, t1 = pp[ i1 ], t0 = pp[ i1 - 1 ]; validate_interval: { seek: { var right; linear_scan: { //- See http://jsperf.com/comparison-to-undefined/3 //- slower code: //- //- if ( t >= t1 || t1 === undefined ) { forward_scan: if ( ! ( t < t1 ) ) { for ( var giveUpAt = i1 + 2; ; ) { if ( t1 === undefined ) { if ( t < t0 ) { break forward_scan; } // after end i1 = pp.length; this._cachedIndex = i1; return this.afterEnd_( i1 - 1, t, t0 ); } if ( i1 === giveUpAt ) { break; } // this loop t0 = t1; t1 = pp[ ++ i1 ]; if ( t < t1 ) { // we have arrived at the sought interval break seek; } } // prepare binary search on the right side of the index right = pp.length; break linear_scan; } //- slower code: //- if ( t < t0 || t0 === undefined ) { if ( ! ( t >= t0 ) ) { // looping? var t1global = pp[ 1 ]; if ( t < t1global ) { i1 = 2; // + 1, using the scan for the details t0 = t1global; } // linear reverse scan for ( var giveUpAt = i1 - 2; ; ) { if ( t0 === undefined ) { // before start this._cachedIndex = 0; return this.beforeStart_( 0, t, t1 ); } if ( i1 === giveUpAt ) { break; } // this loop t1 = t0; t0 = pp[ -- i1 - 1 ]; if ( t >= t0 ) { // we have arrived at the sought interval break seek; } } // prepare binary search on the left side of the index right = i1; i1 = 0; break linear_scan; } // the interval is valid break validate_interval; } // linear scan // binary search while ( i1 < right ) { var mid = ( i1 + right ) >>> 1; if ( t < pp[ mid ] ) { right = mid; } else { i1 = mid + 1; } } t1 = pp[ i1 ]; t0 = pp[ i1 - 1 ]; // check boundary cases, again if ( t0 === undefined ) { this._cachedIndex = 0; return this.beforeStart_( 0, t, t1 ); } if ( t1 === undefined ) { i1 = pp.length; this._cachedIndex = i1; return this.afterEnd_( i1 - 1, t0, t ); } } // seek this._cachedIndex = i1; this.intervalChanged_( i1, t0, t1 ); } // validate_interval return this.interpolate_( i1, t0, t, t1 ); }, settings: null, // optional, subclass-specific settings structure // Note: The indirection allows central control of many interpolants. // --- Protected interface DefaultSettings_: {}, getSettings_: function () { return this.settings || this.DefaultSettings_; }, copySampleValue_: function ( index ) { // copies a sample value to the result buffer var result = this.resultBuffer, values = this.sampleValues, stride = this.valueSize, offset = index * stride; for ( var i = 0; i !== stride; ++ i ) { result[ i ] = values[ offset + i ]; } return result; }, // Template methods for derived classes: interpolate_: function ( /* i1, t0, t, t1 */ ) { throw new Error( 'call to abstract method' ); // implementations shall return this.resultBuffer }, intervalChanged_: function ( /* i1, t0, t1 */ ) { // empty } } ); //!\ DECLARE ALIAS AFTER assign prototype ! Object.assign( Interpolant.prototype, { //( 0, t, t0 ), returns this.resultBuffer beforeStart_: Interpolant.prototype.copySampleValue_, //( N-1, tN-1, t ), returns this.resultBuffer afterEnd_: Interpolant.prototype.copySampleValue_, } ); /** * Fast and simple cubic spline interpolant. * * It was derived from a Hermitian construction setting the first derivative * at each sample position to the linear slope between neighboring positions * over their parameter interval. * * @author tschw */ function CubicInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) { Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer ); this._weightPrev = - 0; this._offsetPrev = - 0; this._weightNext = - 0; this._offsetNext = - 0; } CubicInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), { constructor: CubicInterpolant, DefaultSettings_: { endingStart: ZeroCurvatureEnding, endingEnd: ZeroCurvatureEnding }, intervalChanged_: function ( i1, t0, t1 ) { var pp = this.parameterPositions, iPrev = i1 - 2, iNext = i1 + 1, tPrev = pp[ iPrev ], tNext = pp[ iNext ]; if ( tPrev === undefined ) { switch ( this.getSettings_().endingStart ) { case ZeroSlopeEnding: // f'(t0) = 0 iPrev = i1; tPrev = 2 * t0 - t1; break; case WrapAroundEnding: // use the other end of the curve iPrev = pp.length - 2; tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ]; break; default: // ZeroCurvatureEnding // f''(t0) = 0 a.k.a. Natural Spline iPrev = i1; tPrev = t1; } } if ( tNext === undefined ) { switch ( this.getSettings_().endingEnd ) { case ZeroSlopeEnding: // f'(tN) = 0 iNext = i1; tNext = 2 * t1 - t0; break; case WrapAroundEnding: // use the other end of the curve iNext = 1; tNext = t1 + pp[ 1 ] - pp[ 0 ]; break; default: // ZeroCurvatureEnding // f''(tN) = 0, a.k.a. Natural Spline iNext = i1 - 1; tNext = t0; } } var halfDt = ( t1 - t0 ) * 0.5, stride = this.valueSize; this._weightPrev = halfDt / ( t0 - tPrev ); this._weightNext = halfDt / ( tNext - t1 ); this._offsetPrev = iPrev * stride; this._offsetNext = iNext * stride; }, interpolate_: function ( i1, t0, t, t1 ) { var result = this.resultBuffer, values = this.sampleValues, stride = this.valueSize, o1 = i1 * stride, o0 = o1 - stride, oP = this._offsetPrev, oN = this._offsetNext, wP = this._weightPrev, wN = this._weightNext, p = ( t - t0 ) / ( t1 - t0 ), pp = p * p, ppp = pp * p; // evaluate polynomials var sP = - wP * ppp + 2 * wP * pp - wP * p; var s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1; var s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p; var sN = wN * ppp - wN * pp; // combine data linearly for ( var i = 0; i !== stride; ++ i ) { result[ i ] = sP * values[ oP + i ] + s0 * values[ o0 + i ] + s1 * values[ o1 + i ] + sN * values[ oN + i ]; } return result; } } ); /** * @author tschw */ function LinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) { Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer ); } LinearInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), { constructor: LinearInterpolant, interpolate_: function ( i1, t0, t, t1 ) { var result = this.resultBuffer, values = this.sampleValues, stride = this.valueSize, offset1 = i1 * stride, offset0 = offset1 - stride, weight1 = ( t - t0 ) / ( t1 - t0 ), weight0 = 1 - weight1; for ( var i = 0; i !== stride; ++ i ) { result[ i ] = values[ offset0 + i ] * weight0 + values[ offset1 + i ] * weight1; } return result; } } ); /** * * Interpolant that evaluates to the sample value at the position preceeding * the parameter. * * @author tschw */ function DiscreteInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) { Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer ); } DiscreteInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), { constructor: DiscreteInterpolant, interpolate_: function ( i1 /*, t0, t, t1 */ ) { return this.copySampleValue_( i1 - 1 ); } } ); /** * * A timed sequence of keyframes for a specific property. * * * @author Ben Houston / http://clara.io/ * @author David Sarno / http://lighthaus.us/ * @author tschw */ function KeyframeTrack( name, times, values, interpolation ) { if ( name === undefined ) { throw new Error( 'THREE.KeyframeTrack: track name is undefined' ); } if ( times === undefined || times.length === 0 ) { throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name ); } this.name = name; this.times = AnimationUtils.convertArray( times, this.TimeBufferType ); this.values = AnimationUtils.convertArray( values, this.ValueBufferType ); this.setInterpolation( interpolation || this.DefaultInterpolation ); } // Static methods Object.assign( KeyframeTrack, { // Serialization (in static context, because of constructor invocation // and automatic invocation of .toJSON): toJSON: function ( track ) { var trackType = track.constructor; var json; // derived classes can define a static toJSON method if ( trackType.toJSON !== undefined ) { json = trackType.toJSON( track ); } else { // by default, we assume the data can be serialized as-is json = { 'name': track.name, 'times': AnimationUtils.convertArray( track.times, Array ), 'values': AnimationUtils.convertArray( track.values, Array ) }; var interpolation = track.getInterpolation(); if ( interpolation !== track.DefaultInterpolation ) { json.interpolation = interpolation; } } json.type = track.ValueTypeName; // mandatory return json; } } ); Object.assign( KeyframeTrack.prototype, { constructor: KeyframeTrack, TimeBufferType: Float32Array, ValueBufferType: Float32Array, DefaultInterpolation: InterpolateLinear, InterpolantFactoryMethodDiscrete: function ( result ) { return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result ); }, InterpolantFactoryMethodLinear: function ( result ) { return new LinearInterpolant( this.times, this.values, this.getValueSize(), result ); }, InterpolantFactoryMethodSmooth: function ( result ) { return new CubicInterpolant( this.times, this.values, this.getValueSize(), result ); }, setInterpolation: function ( interpolation ) { var factoryMethod; switch ( interpolation ) { case InterpolateDiscrete: factoryMethod = this.InterpolantFactoryMethodDiscrete; break; case InterpolateLinear: factoryMethod = this.InterpolantFactoryMethodLinear; break; case InterpolateSmooth: factoryMethod = this.InterpolantFactoryMethodSmooth; break; } if ( factoryMethod === undefined ) { var message = "unsupported interpolation for " + this.ValueTypeName + " keyframe track named " + this.name; if ( this.createInterpolant === undefined ) { // fall back to default, unless the default itself is messed up if ( interpolation !== this.DefaultInterpolation ) { this.setInterpolation( this.DefaultInterpolation ); } else { throw new Error( message ); // fatal, in this case } } console.warn( 'THREE.KeyframeTrack:', message ); return this; } this.createInterpolant = factoryMethod; return this; }, getInterpolation: function () { switch ( this.createInterpolant ) { case this.InterpolantFactoryMethodDiscrete: return InterpolateDiscrete; case this.InterpolantFactoryMethodLinear: return InterpolateLinear; case this.InterpolantFactoryMethodSmooth: return InterpolateSmooth; } }, getValueSize: function () { return this.values.length / this.times.length; }, // move all keyframes either forwards or backwards in time shift: function ( timeOffset ) { if ( timeOffset !== 0.0 ) { var times = this.times; for ( var i = 0, n = times.length; i !== n; ++ i ) { times[ i ] += timeOffset; } } return this; }, // scale all keyframe times by a factor (useful for frame <-> seconds conversions) scale: function ( timeScale ) { if ( timeScale !== 1.0 ) { var times = this.times; for ( var i = 0, n = times.length; i !== n; ++ i ) { times[ i ] *= timeScale; } } return this; }, // removes keyframes before and after animation without changing any values within the range [startTime, endTime]. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values trim: function ( startTime, endTime ) { var times = this.times, nKeys = times.length, from = 0, to = nKeys - 1; while ( from !== nKeys && times[ from ] < startTime ) { ++ from; } while ( to !== - 1 && times[ to ] > endTime ) { -- to; } ++ to; // inclusive -> exclusive bound if ( from !== 0 || to !== nKeys ) { // empty tracks are forbidden, so keep at least one keyframe if ( from >= to ) { to = Math.max( to, 1 ), from = to - 1; } var stride = this.getValueSize(); this.times = AnimationUtils.arraySlice( times, from, to ); this.values = AnimationUtils.arraySlice( this.values, from * stride, to * stride ); } return this; }, // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable validate: function () { var valid = true; var valueSize = this.getValueSize(); if ( valueSize - Math.floor( valueSize ) !== 0 ) { console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this ); valid = false; } var times = this.times, values = this.values, nKeys = times.length; if ( nKeys === 0 ) { console.error( 'THREE.KeyframeTrack: Track is empty.', this ); valid = false; } var prevTime = null; for ( var i = 0; i !== nKeys; i ++ ) { var currTime = times[ i ]; if ( typeof currTime === 'number' && isNaN( currTime ) ) { console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime ); valid = false; break; } if ( prevTime !== null && prevTime > currTime ) { console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime ); valid = false; break; } prevTime = currTime; } if ( values !== undefined ) { if ( AnimationUtils.isTypedArray( values ) ) { for ( var i = 0, n = values.length; i !== n; ++ i ) { var value = values[ i ]; if ( isNaN( value ) ) { console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value ); valid = false; break; } } } } return valid; }, // removes equivalent sequential keys as common in morph target sequences // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0) optimize: function () { // times or values may be shared with other tracks, so overwriting is unsafe var times = AnimationUtils.arraySlice( this.times ), values = AnimationUtils.arraySlice( this.values ), stride = this.getValueSize(), smoothInterpolation = this.getInterpolation() === InterpolateSmooth, writeIndex = 1, lastIndex = times.length - 1; for ( var i = 1; i < lastIndex; ++ i ) { var keep = false; var time = times[ i ]; var timeNext = times[ i + 1 ]; // remove adjacent keyframes scheduled at the same time if ( time !== timeNext && ( i !== 1 || time !== time[ 0 ] ) ) { if ( ! smoothInterpolation ) { // remove unnecessary keyframes same as their neighbors var offset = i * stride, offsetP = offset - stride, offsetN = offset + stride; for ( var j = 0; j !== stride; ++ j ) { var value = values[ offset + j ]; if ( value !== values[ offsetP + j ] || value !== values[ offsetN + j ] ) { keep = true; break; } } } else { keep = true; } } // in-place compaction if ( keep ) { if ( i !== writeIndex ) { times[ writeIndex ] = times[ i ]; var readOffset = i * stride, writeOffset = writeIndex * stride; for ( var j = 0; j !== stride; ++ j ) { values[ writeOffset + j ] = values[ readOffset + j ]; } } ++ writeIndex; } } // flush last keyframe (compaction looks ahead) if ( lastIndex > 0 ) { times[ writeIndex ] = times[ lastIndex ]; for ( var readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) { values[ writeOffset + j ] = values[ readOffset + j ]; } ++ writeIndex; } if ( writeIndex !== times.length ) { this.times = AnimationUtils.arraySlice( times, 0, writeIndex ); this.values = AnimationUtils.arraySlice( values, 0, writeIndex * stride ); } else { this.times = times; this.values = values; } return this; }, clone: function () { var times = AnimationUtils.arraySlice( this.times, 0 ); var values = AnimationUtils.arraySlice( this.values, 0 ); var TypedKeyframeTrack = this.constructor; var track = new TypedKeyframeTrack( this.name, times, values ); // Interpolant argument to constructor is not saved, so copy the factory method directly. track.createInterpolant = this.createInterpolant; return track; } } ); /** * * A Track of Boolean keyframe values. * * * @author Ben Houston / http://clara.io/ * @author David Sarno / http://lighthaus.us/ * @author tschw */ function BooleanKeyframeTrack( name, times, values ) { KeyframeTrack.call( this, name, times, values ); } BooleanKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), { constructor: BooleanKeyframeTrack, ValueTypeName: 'bool', ValueBufferType: Array, DefaultInterpolation: InterpolateDiscrete, InterpolantFactoryMethodLinear: undefined, InterpolantFactoryMethodSmooth: undefined // Note: Actually this track could have a optimized / compressed // representation of a single value and a custom interpolant that // computes "firstValue ^ isOdd( index )". } ); /** * * A Track of keyframe values that represent color. * * * @author Ben Houston / http://clara.io/ * @author David Sarno / http://lighthaus.us/ * @author tschw */ function ColorKeyframeTrack( name, times, values, interpolation ) { KeyframeTrack.call( this, name, times, values, interpolation ); } ColorKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), { constructor: ColorKeyframeTrack, ValueTypeName: 'color' // ValueBufferType is inherited // DefaultInterpolation is inherited // Note: Very basic implementation and nothing special yet. // However, this is the place for color space parameterization. } ); /** * * A Track of numeric keyframe values. * * @author Ben Houston / http://clara.io/ * @author David Sarno / http://lighthaus.us/ * @author tschw */ function NumberKeyframeTrack( name, times, values, interpolation ) { KeyframeTrack.call( this, name, times, values, interpolation ); } NumberKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), { constructor: NumberKeyframeTrack, ValueTypeName: 'number' // ValueBufferType is inherited // DefaultInterpolation is inherited } ); /** * Spherical linear unit quaternion interpolant. * * @author tschw */ function QuaternionLinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) { Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer ); } QuaternionLinearInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), { constructor: QuaternionLinearInterpolant, interpolate_: function ( i1, t0, t, t1 ) { var result = this.resultBuffer, values = this.sampleValues, stride = this.valueSize, offset = i1 * stride, alpha = ( t - t0 ) / ( t1 - t0 ); for ( var end = offset + stride; offset !== end; offset += 4 ) { Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha ); } return result; } } ); /** * * A Track of quaternion keyframe values. * * @author Ben Houston / http://clara.io/ * @author David Sarno / http://lighthaus.us/ * @author tschw */ function QuaternionKeyframeTrack( name, times, values, interpolation ) { KeyframeTrack.call( this, name, times, values, interpolation ); } QuaternionKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), { constructor: QuaternionKeyframeTrack, ValueTypeName: 'quaternion', // ValueBufferType is inherited DefaultInterpolation: InterpolateLinear, InterpolantFactoryMethodLinear: function ( result ) { return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result ); }, InterpolantFactoryMethodSmooth: undefined // not yet implemented } ); /** * * A Track that interpolates Strings * * * @author Ben Houston / http://clara.io/ * @author David Sarno / http://lighthaus.us/ * @author tschw */ function StringKeyframeTrack( name, times, values, interpolation ) { KeyframeTrack.call( this, name, times, values, interpolation ); } StringKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), { constructor: StringKeyframeTrack, ValueTypeName: 'string', ValueBufferType: Array, DefaultInterpolation: InterpolateDiscrete, InterpolantFactoryMethodLinear: undefined, InterpolantFactoryMethodSmooth: undefined } ); /** * * A Track of vectored keyframe values. * * * @author Ben Houston / http://clara.io/ * @author David Sarno / http://lighthaus.us/ * @author tschw */ function VectorKeyframeTrack( name, times, values, interpolation ) { KeyframeTrack.call( this, name, times, values, interpolation ); } VectorKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), { constructor: VectorKeyframeTrack, ValueTypeName: 'vector' // ValueBufferType is inherited // DefaultInterpolation is inherited } ); /** * * Reusable set of Tracks that represent an animation. * * @author Ben Houston / http://clara.io/ * @author David Sarno / http://lighthaus.us/ */ function AnimationClip( name, duration, tracks ) { this.name = name; this.tracks = tracks; this.duration = ( duration !== undefined ) ? duration : - 1; this.uuid = MathUtils.generateUUID(); // this means it should figure out its duration by scanning the tracks if ( this.duration < 0 ) { this.resetDuration(); } } function getTrackTypeForValueTypeName( typeName ) { switch ( typeName.toLowerCase() ) { case 'scalar': case 'double': case 'float': case 'number': case 'integer': return NumberKeyframeTrack; case 'vector': case 'vector2': case 'vector3': case 'vector4': return VectorKeyframeTrack; case 'color': return ColorKeyframeTrack; case 'quaternion': return QuaternionKeyframeTrack; case 'bool': case 'boolean': return BooleanKeyframeTrack; case 'string': return StringKeyframeTrack; } throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName ); } function parseKeyframeTrack( json ) { if ( json.type === undefined ) { throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' ); } var trackType = getTrackTypeForValueTypeName( json.type ); if ( json.times === undefined ) { var times = [], values = []; AnimationUtils.flattenJSON( json.keys, times, values, 'value' ); json.times = times; json.values = values; } // derived classes can define a static parse method if ( trackType.parse !== undefined ) { return trackType.parse( json ); } else { // by default, we assume a constructor compatible with the base return new trackType( json.name, json.times, json.values, json.interpolation ); } } Object.assign( AnimationClip, { parse: function ( json ) { var tracks = [], jsonTracks = json.tracks, frameTime = 1.0 / ( json.fps || 1.0 ); for ( var i = 0, n = jsonTracks.length; i !== n; ++ i ) { tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) ); } return new AnimationClip( json.name, json.duration, tracks ); }, toJSON: function ( clip ) { var tracks = [], clipTracks = clip.tracks; var json = { 'name': clip.name, 'duration': clip.duration, 'tracks': tracks, 'uuid': clip.uuid }; for ( var i = 0, n = clipTracks.length; i !== n; ++ i ) { tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) ); } return json; }, CreateFromMorphTargetSequence: function ( name, morphTargetSequence, fps, noLoop ) { var numMorphTargets = morphTargetSequence.length; var tracks = []; for ( var i = 0; i < numMorphTargets; i ++ ) { var times = []; var values = []; times.push( ( i + numMorphTargets - 1 ) % numMorphTargets, i, ( i + 1 ) % numMorphTargets ); values.push( 0, 1, 0 ); var order = AnimationUtils.getKeyframeOrder( times ); times = AnimationUtils.sortedArray( times, 1, order ); values = AnimationUtils.sortedArray( values, 1, order ); // if there is a key at the first frame, duplicate it as the // last frame as well for perfect loop. if ( ! noLoop && times[ 0 ] === 0 ) { times.push( numMorphTargets ); values.push( values[ 0 ] ); } tracks.push( new NumberKeyframeTrack( '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']', times, values ).scale( 1.0 / fps ) ); } return new AnimationClip( name, - 1, tracks ); }, findByName: function ( objectOrClipArray, name ) { var clipArray = objectOrClipArray; if ( ! Array.isArray( objectOrClipArray ) ) { var o = objectOrClipArray; clipArray = o.geometry && o.geometry.animations || o.animations; } for ( var i = 0; i < clipArray.length; i ++ ) { if ( clipArray[ i ].name === name ) { return clipArray[ i ]; } } return null; }, CreateClipsFromMorphTargetSequences: function ( morphTargets, fps, noLoop ) { var animationToMorphTargets = {}; // tested with https://regex101.com/ on trick sequences // such flamingo_flyA_003, flamingo_run1_003, crdeath0059 var pattern = /^([\w-]*?)([\d]+)$/; // sort morph target names into animation groups based // patterns like Walk_001, Walk_002, Run_001, Run_002 for ( var i = 0, il = morphTargets.length; i < il; i ++ ) { var morphTarget = morphTargets[ i ]; var parts = morphTarget.name.match( pattern ); if ( parts && parts.length > 1 ) { var name = parts[ 1 ]; var animationMorphTargets = animationToMorphTargets[ name ]; if ( ! animationMorphTargets ) { animationToMorphTargets[ name ] = animationMorphTargets = []; } animationMorphTargets.push( morphTarget ); } } var clips = []; for ( var name in animationToMorphTargets ) { clips.push( AnimationClip.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) ); } return clips; }, // parse the animation.hierarchy format parseAnimation: function ( animation, bones ) { if ( ! animation ) { console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' ); return null; } var addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) { // only return track if there are actually keys. if ( animationKeys.length !== 0 ) { var times = []; var values = []; AnimationUtils.flattenJSON( animationKeys, times, values, propertyName ); // empty keys are filtered out, so check again if ( times.length !== 0 ) { destTracks.push( new trackType( trackName, times, values ) ); } } }; var tracks = []; var clipName = animation.name || 'default'; // automatic length determination in AnimationClip. var duration = animation.length || - 1; var fps = animation.fps || 30; var hierarchyTracks = animation.hierarchy || []; for ( var h = 0; h < hierarchyTracks.length; h ++ ) { var animationKeys = hierarchyTracks[ h ].keys; // skip empty tracks if ( ! animationKeys || animationKeys.length === 0 ) { continue; } // process morph targets if ( animationKeys[ 0 ].morphTargets ) { // figure out all morph targets used in this track var morphTargetNames = {}; for ( var k = 0; k < animationKeys.length; k ++ ) { if ( animationKeys[ k ].morphTargets ) { for ( var m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) { morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1; } } } // create a track for each morph target with all zero // morphTargetInfluences except for the keys in which // the morphTarget is named. for ( var morphTargetName in morphTargetNames ) { var times = []; var values = []; for ( var m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) { var animationKey = animationKeys[ k ]; times.push( animationKey.time ); values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 ); } tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) ); } duration = morphTargetNames.length * ( fps || 1.0 ); } else { // ...assume skeletal animation var boneName = '.bones[' + bones[ h ].name + ']'; addNonemptyTrack( VectorKeyframeTrack, boneName + '.position', animationKeys, 'pos', tracks ); addNonemptyTrack( QuaternionKeyframeTrack, boneName + '.quaternion', animationKeys, 'rot', tracks ); addNonemptyTrack( VectorKeyframeTrack, boneName + '.scale', animationKeys, 'scl', tracks ); } } if ( tracks.length === 0 ) { return null; } var clip = new AnimationClip( clipName, duration, tracks ); return clip; } } ); Object.assign( AnimationClip.prototype, { resetDuration: function () { var tracks = this.tracks, duration = 0; for ( var i = 0, n = tracks.length; i !== n; ++ i ) { var track = this.tracks[ i ]; duration = Math.max( duration, track.times[ track.times.length - 1 ] ); } this.duration = duration; return this; }, trim: function () { for ( var i = 0; i < this.tracks.length; i ++ ) { this.tracks[ i ].trim( 0, this.duration ); } return this; }, validate: function () { var valid = true; for ( var i = 0; i < this.tracks.length; i ++ ) { valid = valid && this.tracks[ i ].validate(); } return valid; }, optimize: function () { for ( var i = 0; i < this.tracks.length; i ++ ) { this.tracks[ i ].optimize(); } return this; }, clone: function () { var tracks = []; for ( var i = 0; i < this.tracks.length; i ++ ) { tracks.push( this.tracks[ i ].clone() ); } return new AnimationClip( this.name, this.duration, tracks ); } } ); /** * @author mrdoob / http://mrdoob.com/ */ var Cache = { enabled: false, files: {}, add: function ( key, file ) { if ( this.enabled === false ) { return; } // console.log( 'THREE.Cache', 'Adding key:', key ); this.files[ key ] = file; }, get: function ( key ) { if ( this.enabled === false ) { return; } // console.log( 'THREE.Cache', 'Checking key:', key ); return this.files[ key ]; }, remove: function ( key ) { delete this.files[ key ]; }, clear: function () { this.files = {}; } }; /** * @author mrdoob / http://mrdoob.com/ */ function LoadingManager( onLoad, onProgress, onError ) { var scope = this; var isLoading = false; var itemsLoaded = 0; var itemsTotal = 0; var urlModifier = undefined; var handlers = []; // Refer to #5689 for the reason why we don't set .onStart // in the constructor this.onStart = undefined; this.onLoad = onLoad; this.onProgress = onProgress; this.onError = onError; this.itemStart = function ( url ) { itemsTotal ++; if ( isLoading === false ) { if ( scope.onStart !== undefined ) { scope.onStart( url, itemsLoaded, itemsTotal ); } } isLoading = true; }; this.itemEnd = function ( url ) { itemsLoaded ++; if ( scope.onProgress !== undefined ) { scope.onProgress( url, itemsLoaded, itemsTotal ); } if ( itemsLoaded === itemsTotal ) { isLoading = false; if ( scope.onLoad !== undefined ) { scope.onLoad(); } } }; this.itemError = function ( url ) { if ( scope.onError !== undefined ) { scope.onError( url ); } }; this.resolveURL = function ( url ) { if ( urlModifier ) { return urlModifier( url ); } return url; }; this.setURLModifier = function ( transform ) { urlModifier = transform; return this; }; this.addHandler = function ( regex, loader ) { handlers.push( regex, loader ); return this; }; this.removeHandler = function ( regex ) { var index = handlers.indexOf( regex ); if ( index !== - 1 ) { handlers.splice( index, 2 ); } return this; }; this.getHandler = function ( file ) { for ( var i = 0, l = handlers.length; i < l; i += 2 ) { var regex = handlers[ i ]; var loader = handlers[ i + 1 ]; if ( regex.global ) { regex.lastIndex = 0; } // see #17920 if ( regex.test( file ) ) { return loader; } } return null; }; } var DefaultLoadingManager = new LoadingManager(); /** * @author alteredq / http://alteredqualia.com/ */ function Loader( manager ) { this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager; this.crossOrigin = 'anonymous'; this.path = ''; this.resourcePath = ''; } Object.assign( Loader.prototype, { load: function ( /* url, onLoad, onProgress, onError */ ) {}, parse: function ( /* data */ ) {}, setCrossOrigin: function ( crossOrigin ) { this.crossOrigin = crossOrigin; return this; }, setPath: function ( path ) { this.path = path; return this; }, setResourcePath: function ( resourcePath ) { this.resourcePath = resourcePath; return this; } } ); /** * @author mrdoob / http://mrdoob.com/ */ var loading = {}; function FileLoader( manager ) { Loader.call( this, manager ); } FileLoader.prototype = Object.assign( Object.create( Loader.prototype ), { constructor: FileLoader, load: function ( url, onLoad, onProgress, onError ) { if ( url === undefined ) { url = ''; } if ( this.path !== undefined ) { url = this.path + url; } url = this.manager.resolveURL( url ); var scope = this; var cached = Cache.get( url ); if ( cached !== undefined ) { scope.manager.itemStart( url ); setTimeout( function () { if ( onLoad ) { onLoad( cached ); } scope.manager.itemEnd( url ); }, 0 ); return cached; } // Check if request is duplicate if ( loading[ url ] !== undefined ) { loading[ url ].push( { onLoad: onLoad, onProgress: onProgress, onError: onError } ); return; } // Check for data: URI var dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/; var dataUriRegexResult = url.match( dataUriRegex ); // Safari can not handle Data URIs through XMLHttpRequest so process manually if ( dataUriRegexResult ) { var mimeType = dataUriRegexResult[ 1 ]; var isBase64 = !! dataUriRegexResult[ 2 ]; var data = dataUriRegexResult[ 3 ]; data = decodeURIComponent( data ); if ( isBase64 ) { data = atob( data ); } try { var response; var responseType = ( this.responseType || '' ).toLowerCase(); switch ( responseType ) { case 'arraybuffer': case 'blob': var view = new Uint8Array( data.length ); for ( var i = 0; i < data.length; i ++ ) { view[ i ] = data.charCodeAt( i ); } if ( responseType === 'blob' ) { response = new Blob( [ view.buffer ], { type: mimeType } ); } else { response = view.buffer; } break; case 'document': var parser = new DOMParser(); response = parser.parseFromString( data, mimeType ); break; case 'json': response = JSON.parse( data ); break; default: // 'text' or other response = data; break; } // Wait for next browser tick like standard XMLHttpRequest event dispatching does setTimeout( function () { if ( onLoad ) { onLoad( response ); } scope.manager.itemEnd( url ); }, 0 ); } catch ( error ) { // Wait for next browser tick like standard XMLHttpRequest event dispatching does setTimeout( function () { if ( onError ) { onError( error ); } scope.manager.itemError( url ); scope.manager.itemEnd( url ); }, 0 ); } } else { // Initialise array for duplicate requests loading[ url ] = []; loading[ url ].push( { onLoad: onLoad, onProgress: onProgress, onError: onError } ); var request = new XMLHttpRequest(); request.open( 'GET', url, true ); request.addEventListener( 'load', function ( event ) { var response = this.response; var callbacks = loading[ url ]; delete loading[ url ]; if ( this.status === 200 || this.status === 0 ) { // Some browsers return HTTP Status 0 when using non-http protocol // e.g. 'file://' or 'data://'. Handle as success. if ( this.status === 0 ) { console.warn( 'THREE.FileLoader: HTTP Status 0 received.' ); } // Add to cache only on HTTP success, so that we do not cache // error response bodies as proper responses to requests. Cache.add( url, response ); for ( var i = 0, il = callbacks.length; i < il; i ++ ) { var callback = callbacks[ i ]; if ( callback.onLoad ) { callback.onLoad( response ); } } scope.manager.itemEnd( url ); } else { for ( var i = 0, il = callbacks.length; i < il; i ++ ) { var callback = callbacks[ i ]; if ( callback.onError ) { callback.onError( event ); } } scope.manager.itemError( url ); scope.manager.itemEnd( url ); } }, false ); request.addEventListener( 'progress', function ( event ) { var callbacks = loading[ url ]; for ( var i = 0, il = callbacks.length; i < il; i ++ ) { var callback = callbacks[ i ]; if ( callback.onProgress ) { callback.onProgress( event ); } } }, false ); request.addEventListener( 'error', function ( event ) { var callbacks = loading[ url ]; delete loading[ url ]; for ( var i = 0, il = callbacks.length; i < il; i ++ ) { var callback = callbacks[ i ]; if ( callback.onError ) { callback.onError( event ); } } scope.manager.itemError( url ); scope.manager.itemEnd( url ); }, false ); request.addEventListener( 'abort', function ( event ) { var callbacks = loading[ url ]; delete loading[ url ]; for ( var i = 0, il = callbacks.length; i < il; i ++ ) { var callback = callbacks[ i ]; if ( callback.onError ) { callback.onError( event ); } } scope.manager.itemError( url ); scope.manager.itemEnd( url ); }, false ); if ( this.responseType !== undefined ) { request.responseType = this.responseType; } if ( this.withCredentials !== undefined ) { request.withCredentials = this.withCredentials; } if ( request.overrideMimeType ) { request.overrideMimeType( this.mimeType !== undefined ? this.mimeType : 'text/plain' ); } for ( var header in this.requestHeader ) { request.setRequestHeader( header, this.requestHeader[ header ] ); } request.send( null ); } scope.manager.itemStart( url ); return request; }, setResponseType: function ( value ) { this.responseType = value; return this; }, setWithCredentials: function ( value ) { this.withCredentials = value; return this; }, setMimeType: function ( value ) { this.mimeType = value; return this; }, setRequestHeader: function ( value ) { this.requestHeader = value; return this; } } ); /** * @author bhouston / http://clara.io/ */ function AnimationLoader( manager ) { Loader.call( this, manager ); } AnimationLoader.prototype = Object.assign( Object.create( Loader.prototype ), { constructor: AnimationLoader, load: function ( url, onLoad, onProgress, onError ) { var scope = this; var loader = new FileLoader( scope.manager ); loader.setPath( scope.path ); loader.load( url, function ( text ) { onLoad( scope.parse( JSON.parse( text ) ) ); }, onProgress, onError ); }, parse: function ( json ) { var animations = []; for ( var i = 0; i < json.length; i ++ ) { var clip = AnimationClip.parse( json[ i ] ); animations.push( clip ); } return animations; } } ); /** * @author mrdoob / http://mrdoob.com/ * * Abstract Base class to block based textures loader (dds, pvr, ...) * * Sub classes have to implement the parse() method which will be used in load(). */ function CompressedTextureLoader( manager ) { Loader.call( this, manager ); } CompressedTextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), { constructor: CompressedTextureLoader, load: function ( url, onLoad, onProgress, onError ) { var scope = this; var images = []; var texture = new CompressedTexture(); texture.image = images; var loader = new FileLoader( this.manager ); loader.setPath( this.path ); loader.setResponseType( 'arraybuffer' ); function loadTexture( i ) { loader.load( url[ i ], function ( buffer ) { var texDatas = scope.parse( buffer, true ); images[ i ] = { width: texDatas.width, height: texDatas.height, format: texDatas.format, mipmaps: texDatas.mipmaps }; loaded += 1; if ( loaded === 6 ) { if ( texDatas.mipmapCount === 1 ) { texture.minFilter = LinearFilter; } texture.format = texDatas.format; texture.needsUpdate = true; if ( onLoad ) { onLoad( texture ); } } }, onProgress, onError ); } if ( Array.isArray( url ) ) { var loaded = 0; for ( var i = 0, il = url.length; i < il; ++ i ) { loadTexture( i ); } } else { // compressed cubemap texture stored in a single DDS file loader.load( url, function ( buffer ) { var texDatas = scope.parse( buffer, true ); if ( texDatas.isCubemap ) { var faces = texDatas.mipmaps.length / texDatas.mipmapCount; for ( var f = 0; f < faces; f ++ ) { images[ f ] = { mipmaps: [] }; for ( var i = 0; i < texDatas.mipmapCount; i ++ ) { images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] ); images[ f ].format = texDatas.format; images[ f ].width = texDatas.width; images[ f ].height = texDatas.height; } } } else { texture.image.width = texDatas.width; texture.image.height = texDatas.height; texture.mipmaps = texDatas.mipmaps; } if ( texDatas.mipmapCount === 1 ) { texture.minFilter = LinearFilter; } texture.format = texDatas.format; texture.needsUpdate = true; if ( onLoad ) { onLoad( texture ); } }, onProgress, onError ); } return texture; } } ); /** * @author Nikos M. / https://github.com/foo123/ * * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...) * * Sub classes have to implement the parse() method which will be used in load(). */ function DataTextureLoader( manager ) { Loader.call( this, manager ); } DataTextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), { constructor: DataTextureLoader, load: function ( url, onLoad, onProgress, onError ) { var scope = this; var texture = new DataTexture(); var loader = new FileLoader( this.manager ); loader.setResponseType( 'arraybuffer' ); loader.setPath( this.path ); loader.load( url, function ( buffer ) { var texData = scope.parse( buffer ); if ( ! texData ) { return; } if ( texData.image !== undefined ) { texture.image = texData.image; } else if ( texData.data !== undefined ) { texture.image.width = texData.width; texture.image.height = texData.height; texture.image.data = texData.data; } texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping; texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping; texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter; texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter; texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1; if ( texData.format !== undefined ) { texture.format = texData.format; } if ( texData.type !== undefined ) { texture.type = texData.type; } if ( texData.mipmaps !== undefined ) { texture.mipmaps = texData.mipmaps; texture.minFilter = LinearMipmapLinearFilter; // presumably... } if ( texData.mipmapCount === 1 ) { texture.minFilter = LinearFilter; } texture.needsUpdate = true; if ( onLoad ) { onLoad( texture, texData ); } }, onProgress, onError ); return texture; } } ); /** * @author mrdoob / http://mrdoob.com/ */ function ImageLoader( manager ) { Loader.call( this, manager ); } ImageLoader.prototype = Object.assign( Object.create( Loader.prototype ), { constructor: ImageLoader, load: function ( url, onLoad, onProgress, onError ) { if ( this.path !== undefined ) { url = this.path + url; } url = this.manager.resolveURL( url ); var scope = this; var cached = Cache.get( url ); if ( cached !== undefined ) { scope.manager.itemStart( url ); setTimeout( function () { if ( onLoad ) { onLoad( cached ); } scope.manager.itemEnd( url ); }, 0 ); return cached; } var image = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'img' ); function onImageLoad() { image.removeEventListener( 'load', onImageLoad, false ); image.removeEventListener( 'error', onImageError, false ); Cache.add( url, this ); if ( onLoad ) { onLoad( this ); } scope.manager.itemEnd( url ); } function onImageError( event ) { image.removeEventListener( 'load', onImageLoad, false ); image.removeEventListener( 'error', onImageError, false ); if ( onError ) { onError( event ); } scope.manager.itemError( url ); scope.manager.itemEnd( url ); } image.addEventListener( 'load', onImageLoad, false ); image.addEventListener( 'error', onImageError, false ); if ( url.substr( 0, 5 ) !== 'data:' ) { if ( this.crossOrigin !== undefined ) { image.crossOrigin = this.crossOrigin; } } scope.manager.itemStart( url ); image.src = url; return image; } } ); /** * @author mrdoob / http://mrdoob.com/ */ function CubeTextureLoader( manager ) { Loader.call( this, manager ); } CubeTextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), { constructor: CubeTextureLoader, load: function ( urls, onLoad, onProgress, onError ) { var texture = new CubeTexture(); var loader = new ImageLoader( this.manager ); loader.setCrossOrigin( this.crossOrigin ); loader.setPath( this.path ); var loaded = 0; function loadTexture( i ) { loader.load( urls[ i ], function ( image ) { texture.images[ i ] = image; loaded ++; if ( loaded === 6 ) { texture.needsUpdate = true; if ( onLoad ) { onLoad( texture ); } } }, undefined, onError ); } for ( var i = 0; i < urls.length; ++ i ) { loadTexture( i ); } return texture; } } ); /** * @author mrdoob / http://mrdoob.com/ */ function TextureLoader( manager ) { Loader.call( this, manager ); } TextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), { constructor: TextureLoader, load: function ( url, onLoad, onProgress, onError ) { var texture = new Texture(); var loader = new ImageLoader( this.manager ); loader.setCrossOrigin( this.crossOrigin ); loader.setPath( this.path ); loader.load( url, function ( image ) { texture.image = image; // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB. var isJPEG = url.search( /\.jpe?g($|\?)/i ) > 0 || url.search( /^data\:image\/jpeg/ ) === 0; texture.format = isJPEG ? RGBFormat : RGBAFormat; texture.needsUpdate = true; if ( onLoad !== undefined ) { onLoad( texture ); } }, onProgress, onError ); return texture; } } ); /** * @author zz85 / http://www.lab4games.net/zz85/blog * Extensible curve object * * Some common of curve methods: * .getPoint( t, optionalTarget ), .getTangent( t ) * .getPointAt( u, optionalTarget ), .getTangentAt( u ) * .getPoints(), .getSpacedPoints() * .getLength() * .updateArcLengths() * * This following curves inherit from THREE.Curve: * * -- 2D curves -- * THREE.ArcCurve * THREE.CubicBezierCurve * THREE.EllipseCurve * THREE.LineCurve * THREE.QuadraticBezierCurve * THREE.SplineCurve * * -- 3D curves -- * THREE.CatmullRomCurve3 * THREE.CubicBezierCurve3 * THREE.LineCurve3 * THREE.QuadraticBezierCurve3 * * A series of curves can be represented as a THREE.CurvePath. * **/ /************************************************************** * Abstract Curve base class **************************************************************/ function Curve() { this.type = 'Curve'; this.arcLengthDivisions = 200; } Object.assign( Curve.prototype, { // Virtual base class method to overwrite and implement in subclasses // - t [0 .. 1] getPoint: function ( /* t, optionalTarget */ ) { console.warn( 'THREE.Curve: .getPoint() not implemented.' ); return null; }, // Get point at relative position in curve according to arc length // - u [0 .. 1] getPointAt: function ( u, optionalTarget ) { var t = this.getUtoTmapping( u ); return this.getPoint( t, optionalTarget ); }, // Get sequence of points using getPoint( t ) getPoints: function ( divisions ) { if ( divisions === undefined ) { divisions = 5; } var points = []; for ( var d = 0; d <= divisions; d ++ ) { points.push( this.getPoint( d / divisions ) ); } return points; }, // Get sequence of points using getPointAt( u ) getSpacedPoints: function ( divisions ) { if ( divisions === undefined ) { divisions = 5; } var points = []; for ( var d = 0; d <= divisions; d ++ ) { points.push( this.getPointAt( d / divisions ) ); } return points; }, // Get total curve arc length getLength: function () { var lengths = this.getLengths(); return lengths[ lengths.length - 1 ]; }, // Get list of cumulative segment lengths getLengths: function ( divisions ) { if ( divisions === undefined ) { divisions = this.arcLengthDivisions; } if ( this.cacheArcLengths && ( this.cacheArcLengths.length === divisions + 1 ) && ! this.needsUpdate ) { return this.cacheArcLengths; } this.needsUpdate = false; var cache = []; var current, last = this.getPoint( 0 ); var p, sum = 0; cache.push( 0 ); for ( p = 1; p <= divisions; p ++ ) { current = this.getPoint( p / divisions ); sum += current.distanceTo( last ); cache.push( sum ); last = current; } this.cacheArcLengths = cache; return cache; // { sums: cache, sum: sum }; Sum is in the last element. }, updateArcLengths: function () { this.needsUpdate = true; this.getLengths(); }, // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant getUtoTmapping: function ( u, distance ) { var arcLengths = this.getLengths(); var i = 0, il = arcLengths.length; var targetArcLength; // The targeted u distance value to get if ( distance ) { targetArcLength = distance; } else { targetArcLength = u * arcLengths[ il - 1 ]; } // binary search for the index with largest value smaller than target u distance var low = 0, high = il - 1, comparison; while ( low <= high ) { i = Math.floor( low + ( high - low ) / 2 ); // less likely to overflow, though probably not issue here, JS doesn't really have integers, all numbers are floats comparison = arcLengths[ i ] - targetArcLength; if ( comparison < 0 ) { low = i + 1; } else if ( comparison > 0 ) { high = i - 1; } else { high = i; break; // DONE } } i = high; if ( arcLengths[ i ] === targetArcLength ) { return i / ( il - 1 ); } // we could get finer grain at lengths, or use simple interpolation between two points var lengthBefore = arcLengths[ i ]; var lengthAfter = arcLengths[ i + 1 ]; var segmentLength = lengthAfter - lengthBefore; // determine where we are between the 'before' and 'after' points var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength; // add that fractional amount to t var t = ( i + segmentFraction ) / ( il - 1 ); return t; }, // Returns a unit vector tangent at t // In case any sub curve does not implement its tangent derivation, // 2 points a small delta apart will be used to find its gradient // which seems to give a reasonable approximation getTangent: function ( t ) { var delta = 0.0001; var t1 = t - delta; var t2 = t + delta; // Capping in case of danger if ( t1 < 0 ) { t1 = 0; } if ( t2 > 1 ) { t2 = 1; } var pt1 = this.getPoint( t1 ); var pt2 = this.getPoint( t2 ); var vec = pt2.clone().sub( pt1 ); return vec.normalize(); }, getTangentAt: function ( u ) { var t = this.getUtoTmapping( u ); return this.getTangent( t ); }, computeFrenetFrames: function ( segments, closed ) { // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf var normal = new Vector3(); var tangents = []; var normals = []; var binormals = []; var vec = new Vector3(); var mat = new Matrix4(); var i, u, theta; // compute the tangent vectors for each segment on the curve for ( i = 0; i <= segments; i ++ ) { u = i / segments; tangents[ i ] = this.getTangentAt( u ); tangents[ i ].normalize(); } // select an initial normal vector perpendicular to the first tangent vector, // and in the direction of the minimum tangent xyz component normals[ 0 ] = new Vector3(); binormals[ 0 ] = new Vector3(); var min = Number.MAX_VALUE; var tx = Math.abs( tangents[ 0 ].x ); var ty = Math.abs( tangents[ 0 ].y ); var tz = Math.abs( tangents[ 0 ].z ); if ( tx <= min ) { min = tx; normal.set( 1, 0, 0 ); } if ( ty <= min ) { min = ty; normal.set( 0, 1, 0 ); } if ( tz <= min ) { normal.set( 0, 0, 1 ); } vec.crossVectors( tangents[ 0 ], normal ).normalize(); normals[ 0 ].crossVectors( tangents[ 0 ], vec ); binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ); // compute the slowly-varying normal and binormal vectors for each segment on the curve for ( i = 1; i <= segments; i ++ ) { normals[ i ] = normals[ i - 1 ].clone(); binormals[ i ] = binormals[ i - 1 ].clone(); vec.crossVectors( tangents[ i - 1 ], tangents[ i ] ); if ( vec.length() > Number.EPSILON ) { vec.normalize(); theta = Math.acos( MathUtils.clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) ); } binormals[ i ].crossVectors( tangents[ i ], normals[ i ] ); } // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same if ( closed === true ) { theta = Math.acos( MathUtils.clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) ); theta /= segments; if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) { theta = - theta; } for ( i = 1; i <= segments; i ++ ) { // twist a little... normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) ); binormals[ i ].crossVectors( tangents[ i ], normals[ i ] ); } } return { tangents: tangents, normals: normals, binormals: binormals }; }, clone: function () { return new this.constructor().copy( this ); }, copy: function ( source ) { this.arcLengthDivisions = source.arcLengthDivisions; return this; }, toJSON: function () { var data = { metadata: { version: 4.5, type: 'Curve', generator: 'Curve.toJSON' } }; data.arcLengthDivisions = this.arcLengthDivisions; data.type = this.type; return data; }, fromJSON: function ( json ) { this.arcLengthDivisions = json.arcLengthDivisions; return this; } } ); function EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) { Curve.call( this ); this.type = 'EllipseCurve'; this.aX = aX || 0; this.aY = aY || 0; this.xRadius = xRadius || 1; this.yRadius = yRadius || 1; this.aStartAngle = aStartAngle || 0; this.aEndAngle = aEndAngle || 2 * Math.PI; this.aClockwise = aClockwise || false; this.aRotation = aRotation || 0; } EllipseCurve.prototype = Object.create( Curve.prototype ); EllipseCurve.prototype.constructor = EllipseCurve; EllipseCurve.prototype.isEllipseCurve = true; EllipseCurve.prototype.getPoint = function ( t, optionalTarget ) { var point = optionalTarget || new Vector2(); var twoPi = Math.PI * 2; var deltaAngle = this.aEndAngle - this.aStartAngle; var samePoints = Math.abs( deltaAngle ) < Number.EPSILON; // ensures that deltaAngle is 0 .. 2 PI while ( deltaAngle < 0 ) { deltaAngle += twoPi; } while ( deltaAngle > twoPi ) { deltaAngle -= twoPi; } if ( deltaAngle < Number.EPSILON ) { if ( samePoints ) { deltaAngle = 0; } else { deltaAngle = twoPi; } } if ( this.aClockwise === true && ! samePoints ) { if ( deltaAngle === twoPi ) { deltaAngle = - twoPi; } else { deltaAngle = deltaAngle - twoPi; } } var angle = this.aStartAngle + t * deltaAngle; var x = this.aX + this.xRadius * Math.cos( angle ); var y = this.aY + this.yRadius * Math.sin( angle ); if ( this.aRotation !== 0 ) { var cos = Math.cos( this.aRotation ); var sin = Math.sin( this.aRotation ); var tx = x - this.aX; var ty = y - this.aY; // Rotate the point about the center of the ellipse. x = tx * cos - ty * sin + this.aX; y = tx * sin + ty * cos + this.aY; } return point.set( x, y ); }; EllipseCurve.prototype.copy = function ( source ) { Curve.prototype.copy.call( this, source ); this.aX = source.aX; this.aY = source.aY; this.xRadius = source.xRadius; this.yRadius = source.yRadius; this.aStartAngle = source.aStartAngle; this.aEndAngle = source.aEndAngle; this.aClockwise = source.aClockwise; this.aRotation = source.aRotation; return this; }; EllipseCurve.prototype.toJSON = function () { var data = Curve.prototype.toJSON.call( this ); data.aX = this.aX; data.aY = this.aY; data.xRadius = this.xRadius; data.yRadius = this.yRadius; data.aStartAngle = this.aStartAngle; data.aEndAngle = this.aEndAngle; data.aClockwise = this.aClockwise; data.aRotation = this.aRotation; return data; }; EllipseCurve.prototype.fromJSON = function ( json ) { Curve.prototype.fromJSON.call( this, json ); this.aX = json.aX; this.aY = json.aY; this.xRadius = json.xRadius; this.yRadius = json.yRadius; this.aStartAngle = json.aStartAngle; this.aEndAngle = json.aEndAngle; this.aClockwise = json.aClockwise; this.aRotation = json.aRotation; return this; }; function ArcCurve( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise ); this.type = 'ArcCurve'; } ArcCurve.prototype = Object.create( EllipseCurve.prototype ); ArcCurve.prototype.constructor = ArcCurve; ArcCurve.prototype.isArcCurve = true; /** * @author zz85 https://github.com/zz85 * * Centripetal CatmullRom Curve - which is useful for avoiding * cusps and self-intersections in non-uniform catmull rom curves. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf * * curve.type accepts centripetal(default), chordal and catmullrom * curve.tension is used for catmullrom which defaults to 0.5 */ /* Based on an optimized c++ solution in - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/ - http://ideone.com/NoEbVM This CubicPoly class could be used for reusing some variables and calculations, but for three.js curve use, it could be possible inlined and flatten into a single function call which can be placed in CurveUtils. */ function CubicPoly() { var c0 = 0, c1 = 0, c2 = 0, c3 = 0; /* * Compute coefficients for a cubic polynomial * p(s) = c0 + c1*s + c2*s^2 + c3*s^3 * such that * p(0) = x0, p(1) = x1 * and * p'(0) = t0, p'(1) = t1. */ function init( x0, x1, t0, t1 ) { c0 = x0; c1 = t0; c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1; c3 = 2 * x0 - 2 * x1 + t0 + t1; } return { initCatmullRom: function ( x0, x1, x2, x3, tension ) { init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) ); }, initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) { // compute tangents when parameterized in [t1,t2] var t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1; var t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2; // rescale tangents for parametrization in [0,1] t1 *= dt1; t2 *= dt1; init( x1, x2, t1, t2 ); }, calc: function ( t ) { var t2 = t * t; var t3 = t2 * t; return c0 + c1 * t + c2 * t2 + c3 * t3; } }; } // var tmp = new Vector3(); var px = new CubicPoly(), py = new CubicPoly(), pz = new CubicPoly(); function CatmullRomCurve3( points, closed, curveType, tension ) { Curve.call( this ); this.type = 'CatmullRomCurve3'; this.points = points || []; this.closed = closed || false; this.curveType = curveType || 'centripetal'; this.tension = tension || 0.5; } CatmullRomCurve3.prototype = Object.create( Curve.prototype ); CatmullRomCurve3.prototype.constructor = CatmullRomCurve3; CatmullRomCurve3.prototype.isCatmullRomCurve3 = true; CatmullRomCurve3.prototype.getPoint = function ( t, optionalTarget ) { var point = optionalTarget || new Vector3(); var points = this.points; var l = points.length; var p = ( l - ( this.closed ? 0 : 1 ) ) * t; var intPoint = Math.floor( p ); var weight = p - intPoint; if ( this.closed ) { intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l; } else if ( weight === 0 && intPoint === l - 1 ) { intPoint = l - 2; weight = 1; } var p0, p1, p2, p3; // 4 points if ( this.closed || intPoint > 0 ) { p0 = points[ ( intPoint - 1 ) % l ]; } else { // extrapolate first point tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] ); p0 = tmp; } p1 = points[ intPoint % l ]; p2 = points[ ( intPoint + 1 ) % l ]; if ( this.closed || intPoint + 2 < l ) { p3 = points[ ( intPoint + 2 ) % l ]; } else { // extrapolate last point tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] ); p3 = tmp; } if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) { // init Centripetal / Chordal Catmull-Rom var pow = this.curveType === 'chordal' ? 0.5 : 0.25; var dt0 = Math.pow( p0.distanceToSquared( p1 ), pow ); var dt1 = Math.pow( p1.distanceToSquared( p2 ), pow ); var dt2 = Math.pow( p2.distanceToSquared( p3 ), pow ); // safety check for repeated points if ( dt1 < 1e-4 ) { dt1 = 1.0; } if ( dt0 < 1e-4 ) { dt0 = dt1; } if ( dt2 < 1e-4 ) { dt2 = dt1; } px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 ); py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 ); pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 ); } else if ( this.curveType === 'catmullrom' ) { px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension ); py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension ); pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension ); } point.set( px.calc( weight ), py.calc( weight ), pz.calc( weight ) ); return point; }; CatmullRomCurve3.prototype.copy = function ( source ) { Curve.prototype.copy.call( this, source ); this.points = []; for ( var i = 0, l = source.points.length; i < l; i ++ ) { var point = source.points[ i ]; this.points.push( point.clone() ); } this.closed = source.closed; this.curveType = source.curveType; this.tension = source.tension; return this; }; CatmullRomCurve3.prototype.toJSON = function () { var data = Curve.prototype.toJSON.call( this ); data.points = []; for ( var i = 0, l = this.points.length; i < l; i ++ ) { var point = this.points[ i ]; data.points.push( point.toArray() ); } data.closed = this.closed; data.curveType = this.curveType; data.tension = this.tension; return data; }; CatmullRomCurve3.prototype.fromJSON = function ( json ) { Curve.prototype.fromJSON.call( this, json ); this.points = []; for ( var i = 0, l = json.points.length; i < l; i ++ ) { var point = json.points[ i ]; this.points.push( new Vector3().fromArray( point ) ); } this.closed = json.closed; this.curveType = json.curveType; this.tension = json.tension; return this; }; /** * @author zz85 / http://www.lab4games.net/zz85/blog * * Bezier Curves formulas obtained from * http://en.wikipedia.org/wiki/Bézier_curve */ function CatmullRom( t, p0, p1, p2, p3 ) { var v0 = ( p2 - p0 ) * 0.5; var v1 = ( p3 - p1 ) * 0.5; var t2 = t * t; var t3 = t * t2; return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1; } // function QuadraticBezierP0( t, p ) { var k = 1 - t; return k * k * p; } function QuadraticBezierP1( t, p ) { return 2 * ( 1 - t ) * t * p; } function QuadraticBezierP2( t, p ) { return t * t * p; } function QuadraticBezier( t, p0, p1, p2 ) { return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) + QuadraticBezierP2( t, p2 ); } // function CubicBezierP0( t, p ) { var k = 1 - t; return k * k * k * p; } function CubicBezierP1( t, p ) { var k = 1 - t; return 3 * k * k * t * p; } function CubicBezierP2( t, p ) { return 3 * ( 1 - t ) * t * t * p; } function CubicBezierP3( t, p ) { return t * t * t * p; } function CubicBezier( t, p0, p1, p2, p3 ) { return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) + CubicBezierP3( t, p3 ); } function CubicBezierCurve( v0, v1, v2, v3 ) { Curve.call( this ); this.type = 'CubicBezierCurve'; this.v0 = v0 || new Vector2(); this.v1 = v1 || new Vector2(); this.v2 = v2 || new Vector2(); this.v3 = v3 || new Vector2(); } CubicBezierCurve.prototype = Object.create( Curve.prototype ); CubicBezierCurve.prototype.constructor = CubicBezierCurve; CubicBezierCurve.prototype.isCubicBezierCurve = true; CubicBezierCurve.prototype.getPoint = function ( t, optionalTarget ) { var point = optionalTarget || new Vector2(); var v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3; point.set( CubicBezier( t, v0.x, v1.x, v2.x, v3.x ), CubicBezier( t, v0.y, v1.y, v2.y, v3.y ) ); return point; }; CubicBezierCurve.prototype.copy = function ( source ) { Curve.prototype.copy.call( this, source ); this.v0.copy( source.v0 ); this.v1.copy( source.v1 ); this.v2.copy( source.v2 ); this.v3.copy( source.v3 ); return this; }; CubicBezierCurve.prototype.toJSON = function () { var data = Curve.prototype.toJSON.call( this ); data.v0 = this.v0.toArray(); data.v1 = this.v1.toArray(); data.v2 = this.v2.toArray(); data.v3 = this.v3.toArray(); return data; }; CubicBezierCurve.prototype.fromJSON = function ( json ) { Curve.prototype.fromJSON.call( this, json ); this.v0.fromArray( json.v0 ); this.v1.fromArray( json.v1 ); this.v2.fromArray( json.v2 ); this.v3.fromArray( json.v3 ); return this; }; function CubicBezierCurve3( v0, v1, v2, v3 ) { Curve.call( this ); this.type = 'CubicBezierCurve3'; this.v0 = v0 || new Vector3(); this.v1 = v1 || new Vector3(); this.v2 = v2 || new Vector3(); this.v3 = v3 || new Vector3(); } CubicBezierCurve3.prototype = Object.create( Curve.prototype ); CubicBezierCurve3.prototype.constructor = CubicBezierCurve3; CubicBezierCurve3.prototype.isCubicBezierCurve3 = true; CubicBezierCurve3.prototype.getPoint = function ( t, optionalTarget ) { var point = optionalTarget || new Vector3(); var v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3; point.set( CubicBezier( t, v0.x, v1.x, v2.x, v3.x ), CubicBezier( t, v0.y, v1.y, v2.y, v3.y ), CubicBezier( t, v0.z, v1.z, v2.z, v3.z ) ); return point; }; CubicBezierCurve3.prototype.copy = function ( source ) { Curve.prototype.copy.call( this, source ); this.v0.copy( source.v0 ); this.v1.copy( source.v1 ); this.v2.copy( source.v2 ); this.v3.copy( source.v3 ); return this; }; CubicBezierCurve3.prototype.toJSON = function () { var data = Curve.prototype.toJSON.call( this ); data.v0 = this.v0.toArray(); data.v1 = this.v1.toArray(); data.v2 = this.v2.toArray(); data.v3 = this.v3.toArray(); return data; }; CubicBezierCurve3.prototype.fromJSON = function ( json ) { Curve.prototype.fromJSON.call( this, json ); this.v0.fromArray( json.v0 ); this.v1.fromArray( json.v1 ); this.v2.fromArray( json.v2 ); this.v3.fromArray( json.v3 ); return this; }; function LineCurve( v1, v2 ) { Curve.call( this ); this.type = 'LineCurve'; this.v1 = v1 || new Vector2(); this.v2 = v2 || new Vector2(); } LineCurve.prototype = Object.create( Curve.prototype ); LineCurve.prototype.constructor = LineCurve; LineCurve.prototype.isLineCurve = true; LineCurve.prototype.getPoint = function ( t, optionalTarget ) { var point = optionalTarget || new Vector2(); if ( t === 1 ) { point.copy( this.v2 ); } else { point.copy( this.v2 ).sub( this.v1 ); point.multiplyScalar( t ).add( this.v1 ); } return point; }; // Line curve is linear, so we can overwrite default getPointAt LineCurve.prototype.getPointAt = function ( u, optionalTarget ) { return this.getPoint( u, optionalTarget ); }; LineCurve.prototype.getTangent = function ( /* t */ ) { var tangent = this.v2.clone().sub( this.v1 ); return tangent.normalize(); }; LineCurve.prototype.copy = function ( source ) { Curve.prototype.copy.call( this, source ); this.v1.copy( source.v1 ); this.v2.copy( source.v2 ); return this; }; LineCurve.prototype.toJSON = function () { var data = Curve.prototype.toJSON.call( this ); data.v1 = this.v1.toArray(); data.v2 = this.v2.toArray(); return data; }; LineCurve.prototype.fromJSON = function ( json ) { Curve.prototype.fromJSON.call( this, json ); this.v1.fromArray( json.v1 ); this.v2.fromArray( json.v2 ); return this; }; function LineCurve3( v1, v2 ) { Curve.call( this ); this.type = 'LineCurve3'; this.v1 = v1 || new Vector3(); this.v2 = v2 || new Vector3(); } LineCurve3.prototype = Object.create( Curve.prototype ); LineCurve3.prototype.constructor = LineCurve3; LineCurve3.prototype.isLineCurve3 = true; LineCurve3.prototype.getPoint = function ( t, optionalTarget ) { var point = optionalTarget || new Vector3(); if ( t === 1 ) { point.copy( this.v2 ); } else { point.copy( this.v2 ).sub( this.v1 ); point.multiplyScalar( t ).add( this.v1 ); } return point; }; // Line curve is linear, so we can overwrite default getPointAt LineCurve3.prototype.getPointAt = function ( u, optionalTarget ) { return this.getPoint( u, optionalTarget ); }; LineCurve3.prototype.copy = function ( source ) { Curve.prototype.copy.call( this, source ); this.v1.copy( source.v1 ); this.v2.copy( source.v2 ); return this; }; LineCurve3.prototype.toJSON = function () { var data = Curve.prototype.toJSON.call( this ); data.v1 = this.v1.toArray(); data.v2 = this.v2.toArray(); return data; }; LineCurve3.prototype.fromJSON = function ( json ) { Curve.prototype.fromJSON.call( this, json ); this.v1.fromArray( json.v1 ); this.v2.fromArray( json.v2 ); return this; }; function QuadraticBezierCurve( v0, v1, v2 ) { Curve.call( this ); this.type = 'QuadraticBezierCurve'; this.v0 = v0 || new Vector2(); this.v1 = v1 || new Vector2(); this.v2 = v2 || new Vector2(); } QuadraticBezierCurve.prototype = Object.create( Curve.prototype ); QuadraticBezierCurve.prototype.constructor = QuadraticBezierCurve; QuadraticBezierCurve.prototype.isQuadraticBezierCurve = true; QuadraticBezierCurve.prototype.getPoint = function ( t, optionalTarget ) { var point = optionalTarget || new Vector2(); var v0 = this.v0, v1 = this.v1, v2 = this.v2; point.set( QuadraticBezier( t, v0.x, v1.x, v2.x ), QuadraticBezier( t, v0.y, v1.y, v2.y ) ); return point; }; QuadraticBezierCurve.prototype.copy = function ( source ) { Curve.prototype.copy.call( this, source ); this.v0.copy( source.v0 ); this.v1.copy( source.v1 ); this.v2.copy( source.v2 ); return this; }; QuadraticBezierCurve.prototype.toJSON = function () { var data = Curve.prototype.toJSON.call( this ); data.v0 = this.v0.toArray(); data.v1 = this.v1.toArray(); data.v2 = this.v2.toArray(); return data; }; QuadraticBezierCurve.prototype.fromJSON = function ( json ) { Curve.prototype.fromJSON.call( this, json ); this.v0.fromArray( json.v0 ); this.v1.fromArray( json.v1 ); this.v2.fromArray( json.v2 ); return this; }; function QuadraticBezierCurve3( v0, v1, v2 ) { Curve.call( this ); this.type = 'QuadraticBezierCurve3'; this.v0 = v0 || new Vector3(); this.v1 = v1 || new Vector3(); this.v2 = v2 || new Vector3(); } QuadraticBezierCurve3.prototype = Object.create( Curve.prototype ); QuadraticBezierCurve3.prototype.constructor = QuadraticBezierCurve3; QuadraticBezierCurve3.prototype.isQuadraticBezierCurve3 = true; QuadraticBezierCurve3.prototype.getPoint = function ( t, optionalTarget ) { var point = optionalTarget || new Vector3(); var v0 = this.v0, v1 = this.v1, v2 = this.v2; point.set( QuadraticBezier( t, v0.x, v1.x, v2.x ), QuadraticBezier( t, v0.y, v1.y, v2.y ), QuadraticBezier( t, v0.z, v1.z, v2.z ) ); return point; }; QuadraticBezierCurve3.prototype.copy = function ( source ) { Curve.prototype.copy.call( this, source ); this.v0.copy( source.v0 ); this.v1.copy( source.v1 ); this.v2.copy( source.v2 ); return this; }; QuadraticBezierCurve3.prototype.toJSON = function () { var data = Curve.prototype.toJSON.call( this ); data.v0 = this.v0.toArray(); data.v1 = this.v1.toArray(); data.v2 = this.v2.toArray(); return data; }; QuadraticBezierCurve3.prototype.fromJSON = function ( json ) { Curve.prototype.fromJSON.call( this, json ); this.v0.fromArray( json.v0 ); this.v1.fromArray( json.v1 ); this.v2.fromArray( json.v2 ); return this; }; function SplineCurve( points /* array of Vector2 */ ) { Curve.call( this ); this.type = 'SplineCurve'; this.points = points || []; } SplineCurve.prototype = Object.create( Curve.prototype ); SplineCurve.prototype.constructor = SplineCurve; SplineCurve.prototype.isSplineCurve = true; SplineCurve.prototype.getPoint = function ( t, optionalTarget ) { var point = optionalTarget || new Vector2(); var points = this.points; var p = ( points.length - 1 ) * t; var intPoint = Math.floor( p ); var weight = p - intPoint; var p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ]; var p1 = points[ intPoint ]; var p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ]; var p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ]; point.set( CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ), CatmullRom( weight, p0.y, p1.y, p2.y, p3.y ) ); return point; }; SplineCurve.prototype.copy = function ( source ) { Curve.prototype.copy.call( this, source ); this.points = []; for ( var i = 0, l = source.points.length; i < l; i ++ ) { var point = source.points[ i ]; this.points.push( point.clone() ); } return this; }; SplineCurve.prototype.toJSON = function () { var data = Curve.prototype.toJSON.call( this ); data.points = []; for ( var i = 0, l = this.points.length; i < l; i ++ ) { var point = this.points[ i ]; data.points.push( point.toArray() ); } return data; }; SplineCurve.prototype.fromJSON = function ( json ) { Curve.prototype.fromJSON.call( this, json ); this.points = []; for ( var i = 0, l = json.points.length; i < l; i ++ ) { var point = json.points[ i ]; this.points.push( new Vector2().fromArray( point ) ); } return this; }; var Curves = /*#__PURE__*/Object.freeze({ __proto__: null, ArcCurve: ArcCurve, CatmullRomCurve3: CatmullRomCurve3, CubicBezierCurve: CubicBezierCurve, CubicBezierCurve3: CubicBezierCurve3, EllipseCurve: EllipseCurve, LineCurve: LineCurve, LineCurve3: LineCurve3, QuadraticBezierCurve: QuadraticBezierCurve, QuadraticBezierCurve3: QuadraticBezierCurve3, SplineCurve: SplineCurve }); /** * @author zz85 / http://www.lab4games.net/zz85/blog * **/ /************************************************************** * Curved Path - a curve path is simply a array of connected * curves, but retains the api of a curve **************************************************************/ function CurvePath() { Curve.call( this ); this.type = 'CurvePath'; this.curves = []; this.autoClose = false; // Automatically closes the path } CurvePath.prototype = Object.assign( Object.create( Curve.prototype ), { constructor: CurvePath, add: function ( curve ) { this.curves.push( curve ); }, closePath: function () { // Add a line curve if start and end of lines are not connected var startPoint = this.curves[ 0 ].getPoint( 0 ); var endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 ); if ( ! startPoint.equals( endPoint ) ) { this.curves.push( new LineCurve( endPoint, startPoint ) ); } }, // To get accurate point with reference to // entire path distance at time t, // following has to be done: // 1. Length of each sub path have to be known // 2. Locate and identify type of curve // 3. Get t for the curve // 4. Return curve.getPointAt(t') getPoint: function ( t ) { var d = t * this.getLength(); var curveLengths = this.getCurveLengths(); var i = 0; // To think about boundaries points. while ( i < curveLengths.length ) { if ( curveLengths[ i ] >= d ) { var diff = curveLengths[ i ] - d; var curve = this.curves[ i ]; var segmentLength = curve.getLength(); var u = segmentLength === 0 ? 0 : 1 - diff / segmentLength; return curve.getPointAt( u ); } i ++; } return null; // loop where sum != 0, sum > d , sum+1 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) { points.push( points[ 0 ] ); } return points; }, copy: function ( source ) { Curve.prototype.copy.call( this, source ); this.curves = []; for ( var i = 0, l = source.curves.length; i < l; i ++ ) { var curve = source.curves[ i ]; this.curves.push( curve.clone() ); } this.autoClose = source.autoClose; return this; }, toJSON: function () { var data = Curve.prototype.toJSON.call( this ); data.autoClose = this.autoClose; data.curves = []; for ( var i = 0, l = this.curves.length; i < l; i ++ ) { var curve = this.curves[ i ]; data.curves.push( curve.toJSON() ); } return data; }, fromJSON: function ( json ) { Curve.prototype.fromJSON.call( this, json ); this.autoClose = json.autoClose; this.curves = []; for ( var i = 0, l = json.curves.length; i < l; i ++ ) { var curve = json.curves[ i ]; this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) ); } return this; } } ); /** * @author zz85 / http://www.lab4games.net/zz85/blog * Creates free form 2d path using series of points, lines or curves. **/ function Path( points ) { CurvePath.call( this ); this.type = 'Path'; this.currentPoint = new Vector2(); if ( points ) { this.setFromPoints( points ); } } Path.prototype = Object.assign( Object.create( CurvePath.prototype ), { constructor: Path, setFromPoints: function ( points ) { this.moveTo( points[ 0 ].x, points[ 0 ].y ); for ( var i = 1, l = points.length; i < l; i ++ ) { this.lineTo( points[ i ].x, points[ i ].y ); } return this; }, moveTo: function ( x, y ) { this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying? return this; }, lineTo: function ( x, y ) { var curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) ); this.curves.push( curve ); this.currentPoint.set( x, y ); return this; }, quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) { var curve = new QuadraticBezierCurve( this.currentPoint.clone(), new Vector2( aCPx, aCPy ), new Vector2( aX, aY ) ); this.curves.push( curve ); this.currentPoint.set( aX, aY ); return this; }, bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) { var curve = new CubicBezierCurve( this.currentPoint.clone(), new Vector2( aCP1x, aCP1y ), new Vector2( aCP2x, aCP2y ), new Vector2( aX, aY ) ); this.curves.push( curve ); this.currentPoint.set( aX, aY ); return this; }, splineThru: function ( pts /*Array of Vector*/ ) { var npts = [ this.currentPoint.clone() ].concat( pts ); var curve = new SplineCurve( npts ); this.curves.push( curve ); this.currentPoint.copy( pts[ pts.length - 1 ] ); return this; }, arc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { var x0 = this.currentPoint.x; var y0 = this.currentPoint.y; this.absarc( aX + x0, aY + y0, aRadius, aStartAngle, aEndAngle, aClockwise ); return this; }, absarc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) { this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise ); return this; }, ellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) { var x0 = this.currentPoint.x; var y0 = this.currentPoint.y; this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ); return this; }, absellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) { var curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ); if ( this.curves.length > 0 ) { // if a previous curve is present, attempt to join var firstPoint = curve.getPoint( 0 ); if ( ! firstPoint.equals( this.currentPoint ) ) { this.lineTo( firstPoint.x, firstPoint.y ); } } this.curves.push( curve ); var lastPoint = curve.getPoint( 1 ); this.currentPoint.copy( lastPoint ); return this; }, copy: function ( source ) { CurvePath.prototype.copy.call( this, source ); this.currentPoint.copy( source.currentPoint ); return this; }, toJSON: function () { var data = CurvePath.prototype.toJSON.call( this ); data.currentPoint = this.currentPoint.toArray(); return data; }, fromJSON: function ( json ) { CurvePath.prototype.fromJSON.call( this, json ); this.currentPoint.fromArray( json.currentPoint ); return this; } } ); /** * @author zz85 / http://www.lab4games.net/zz85/blog * Defines a 2d shape plane using paths. **/ // STEP 1 Create a path. // STEP 2 Turn path into shape. // STEP 3 ExtrudeGeometry takes in Shape/Shapes // STEP 3a - Extract points from each shape, turn to vertices // STEP 3b - Triangulate each shape, add faces. function Shape( points ) { Path.call( this, points ); this.uuid = MathUtils.generateUUID(); this.type = 'Shape'; this.holes = []; } Shape.prototype = Object.assign( Object.create( Path.prototype ), { constructor: Shape, getPointsHoles: function ( divisions ) { var holesPts = []; for ( var i = 0, l = this.holes.length; i < l; i ++ ) { holesPts[ i ] = this.holes[ i ].getPoints( divisions ); } return holesPts; }, // get points of shape and holes (keypoints based on segments parameter) extractPoints: function ( divisions ) { return { shape: this.getPoints( divisions ), holes: this.getPointsHoles( divisions ) }; }, copy: function ( source ) { Path.prototype.copy.call( this, source ); this.holes = []; for ( var i = 0, l = source.holes.length; i < l; i ++ ) { var hole = source.holes[ i ]; this.holes.push( hole.clone() ); } return this; }, toJSON: function () { var data = Path.prototype.toJSON.call( this ); data.uuid = this.uuid; data.holes = []; for ( var i = 0, l = this.holes.length; i < l; i ++ ) { var hole = this.holes[ i ]; data.holes.push( hole.toJSON() ); } return data; }, fromJSON: function ( json ) { Path.prototype.fromJSON.call( this, json ); this.uuid = json.uuid; this.holes = []; for ( var i = 0, l = json.holes.length; i < l; i ++ ) { var hole = json.holes[ i ]; this.holes.push( new Path().fromJSON( hole ) ); } return this; } } ); /** * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ */ function Light( color, intensity ) { Object3D.call( this ); this.type = 'Light'; this.color = new Color( color ); this.intensity = intensity !== undefined ? intensity : 1; this.receiveShadow = undefined; } Light.prototype = Object.assign( Object.create( Object3D.prototype ), { constructor: Light, isLight: true, copy: function ( source ) { Object3D.prototype.copy.call( this, source ); this.color.copy( source.color ); this.intensity = source.intensity; return this; }, toJSON: function ( meta ) { var data = Object3D.prototype.toJSON.call( this, meta ); data.object.color = this.color.getHex(); data.object.intensity = this.intensity; if ( this.groundColor !== undefined ) { data.object.groundColor = this.groundColor.getHex(); } if ( this.distance !== undefined ) { data.object.distance = this.distance; } if ( this.angle !== undefined ) { data.object.angle = this.angle; } if ( this.decay !== undefined ) { data.object.decay = this.decay; } if ( this.penumbra !== undefined ) { data.object.penumbra = this.penumbra; } if ( this.shadow !== undefined ) { data.object.shadow = this.shadow.toJSON(); } return data; } } ); /** * @author alteredq / http://alteredqualia.com/ */ function HemisphereLight( skyColor, groundColor, intensity ) { Light.call( this, skyColor, intensity ); this.type = 'HemisphereLight'; this.castShadow = undefined; this.position.copy( Object3D.DefaultUp ); this.updateMatrix(); this.groundColor = new Color( groundColor ); } HemisphereLight.prototype = Object.assign( Object.create( Light.prototype ), { constructor: HemisphereLight, isHemisphereLight: true, copy: function ( source ) { Light.prototype.copy.call( this, source ); this.groundColor.copy( source.groundColor ); return this; } } ); /** * @author mrdoob / http://mrdoob.com/ */ function LightShadow( camera ) { this.camera = camera; this.bias = 0; this.radius = 1; this.mapSize = new Vector2( 512, 512 ); this.map = null; this.mapPass = null; this.matrix = new Matrix4(); this._frustum = new Frustum(); this._frameExtents = new Vector2( 1, 1 ); this._viewportCount = 1; this._viewports = [ new Vector4( 0, 0, 1, 1 ) ]; } Object.assign( LightShadow.prototype, { _projScreenMatrix: new Matrix4(), _lightPositionWorld: new Vector3(), _lookTarget: new Vector3(), getViewportCount: function () { return this._viewportCount; }, getFrustum: function () { return this._frustum; }, updateMatrices: function ( light ) { var shadowCamera = this.camera, shadowMatrix = this.matrix, projScreenMatrix = this._projScreenMatrix, lookTarget = this._lookTarget, lightPositionWorld = this._lightPositionWorld; lightPositionWorld.setFromMatrixPosition( light.matrixWorld ); shadowCamera.position.copy( lightPositionWorld ); lookTarget.setFromMatrixPosition( light.target.matrixWorld ); shadowCamera.lookAt( lookTarget ); shadowCamera.updateMatrixWorld(); projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse ); this._frustum.setFromProjectionMatrix( projScreenMatrix ); shadowMatrix.set( 0.5, 0.0, 0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 1.0 ); shadowMatrix.multiply( shadowCamera.projectionMatrix ); shadowMatrix.multiply( shadowCamera.matrixWorldInverse ); }, getViewport: function ( viewportIndex ) { return this._viewports[ viewportIndex ]; }, getFrameExtents: function () { return this._frameExtents; }, copy: function ( source ) { this.camera = source.camera.clone(); this.bias = source.bias; this.radius = source.radius; this.mapSize.copy( source.mapSize ); return this; }, clone: function () { return new this.constructor().copy( this ); }, toJSON: function () { var object = {}; if ( this.bias !== 0 ) { object.bias = this.bias; } if ( this.radius !== 1 ) { object.radius = this.radius; } if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) { object.mapSize = this.mapSize.toArray(); } object.camera = this.camera.toJSON( false ).object; delete object.camera.matrix; return object; } } ); /** * @author mrdoob / http://mrdoob.com/ */ function SpotLightShadow() { LightShadow.call( this, new PerspectiveCamera( 50, 1, 0.5, 500 ) ); } SpotLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), { constructor: SpotLightShadow, isSpotLightShadow: true, updateMatrices: function ( light ) { var camera = this.camera; var fov = MathUtils.RAD2DEG * 2 * light.angle; var aspect = this.mapSize.width / this.mapSize.height; var far = light.distance || camera.far; if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) { camera.fov = fov; camera.aspect = aspect; camera.far = far; camera.updateProjectionMatrix(); } LightShadow.prototype.updateMatrices.call( this, light ); } } ); /** * @author alteredq / http://alteredqualia.com/ */ function SpotLight( color, intensity, distance, angle, penumbra, decay ) { Light.call( this, color, intensity ); this.type = 'SpotLight'; this.position.copy( Object3D.DefaultUp ); this.updateMatrix(); this.target = new Object3D(); Object.defineProperty( this, 'power', { get: function () { // intensity = power per solid angle. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf return this.intensity * Math.PI; }, set: function ( power ) { // intensity = power per solid angle. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf this.intensity = power / Math.PI; } } ); this.distance = ( distance !== undefined ) ? distance : 0; this.angle = ( angle !== undefined ) ? angle : Math.PI / 3; this.penumbra = ( penumbra !== undefined ) ? penumbra : 0; this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2. this.shadow = new SpotLightShadow(); } SpotLight.prototype = Object.assign( Object.create( Light.prototype ), { constructor: SpotLight, isSpotLight: true, copy: function ( source ) { Light.prototype.copy.call( this, source ); this.distance = source.distance; this.angle = source.angle; this.penumbra = source.penumbra; this.decay = source.decay; this.target = source.target.clone(); this.shadow = source.shadow.clone(); return this; } } ); function PointLightShadow() { LightShadow.call( this, new PerspectiveCamera( 90, 1, 0.5, 500 ) ); this._frameExtents = new Vector2( 4, 2 ); this._viewportCount = 6; this._viewports = [ // These viewports map a cube-map onto a 2D texture with the // following orientation: // // xzXZ // y Y // // X - Positive x direction // x - Negative x direction // Y - Positive y direction // y - Negative y direction // Z - Positive z direction // z - Negative z direction // positive X new Vector4( 2, 1, 1, 1 ), // negative X new Vector4( 0, 1, 1, 1 ), // positive Z new Vector4( 3, 1, 1, 1 ), // negative Z new Vector4( 1, 1, 1, 1 ), // positive Y new Vector4( 3, 0, 1, 1 ), // negative Y new Vector4( 1, 0, 1, 1 ) ]; this._cubeDirections = [ new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 ) ]; this._cubeUps = [ new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 ) ]; } PointLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), { constructor: PointLightShadow, isPointLightShadow: true, updateMatrices: function ( light, viewportIndex ) { if ( viewportIndex === undefined ) { viewportIndex = 0; } var camera = this.camera, shadowMatrix = this.matrix, lightPositionWorld = this._lightPositionWorld, lookTarget = this._lookTarget, projScreenMatrix = this._projScreenMatrix; lightPositionWorld.setFromMatrixPosition( light.matrixWorld ); camera.position.copy( lightPositionWorld ); lookTarget.copy( camera.position ); lookTarget.add( this._cubeDirections[ viewportIndex ] ); camera.up.copy( this._cubeUps[ viewportIndex ] ); camera.lookAt( lookTarget ); camera.updateMatrixWorld(); shadowMatrix.makeTranslation( - lightPositionWorld.x, - lightPositionWorld.y, - lightPositionWorld.z ); projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse ); this._frustum.setFromProjectionMatrix( projScreenMatrix ); } } ); /** * @author mrdoob / http://mrdoob.com/ */ function PointLight( color, intensity, distance, decay ) { Light.call( this, color, intensity ); this.type = 'PointLight'; Object.defineProperty( this, 'power', { get: function () { // intensity = power per solid angle. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf return this.intensity * 4 * Math.PI; }, set: function ( power ) { // intensity = power per solid angle. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf this.intensity = power / ( 4 * Math.PI ); } } ); this.distance = ( distance !== undefined ) ? distance : 0; this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2. this.shadow = new PointLightShadow(); } PointLight.prototype = Object.assign( Object.create( Light.prototype ), { constructor: PointLight, isPointLight: true, copy: function ( source ) { Light.prototype.copy.call( this, source ); this.distance = source.distance; this.decay = source.decay; this.shadow = source.shadow.clone(); return this; } } ); /** * @author alteredq / http://alteredqualia.com/ * @author arose / http://github.com/arose */ function OrthographicCamera( left, right, top, bottom, near, far ) { Camera.call( this ); this.type = 'OrthographicCamera'; this.zoom = 1; this.view = null; this.left = ( left !== undefined ) ? left : - 1; this.right = ( right !== undefined ) ? right : 1; this.top = ( top !== undefined ) ? top : 1; this.bottom = ( bottom !== undefined ) ? bottom : - 1; this.near = ( near !== undefined ) ? near : 0.1; this.far = ( far !== undefined ) ? far : 2000; this.updateProjectionMatrix(); } OrthographicCamera.prototype = Object.assign( Object.create( Camera.prototype ), { constructor: OrthographicCamera, isOrthographicCamera: true, copy: function ( source, recursive ) { Camera.prototype.copy.call( this, source, recursive ); this.left = source.left; this.right = source.right; this.top = source.top; this.bottom = source.bottom; this.near = source.near; this.far = source.far; this.zoom = source.zoom; this.view = source.view === null ? null : Object.assign( {}, source.view ); return this; }, setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) { if ( this.view === null ) { this.view = { enabled: true, fullWidth: 1, fullHeight: 1, offsetX: 0, offsetY: 0, width: 1, height: 1 }; } this.view.enabled = true; this.view.fullWidth = fullWidth; this.view.fullHeight = fullHeight; this.view.offsetX = x; this.view.offsetY = y; this.view.width = width; this.view.height = height; this.updateProjectionMatrix(); }, clearViewOffset: function () { if ( this.view !== null ) { this.view.enabled = false; } this.updateProjectionMatrix(); }, updateProjectionMatrix: function () { var dx = ( this.right - this.left ) / ( 2 * this.zoom ); var dy = ( this.top - this.bottom ) / ( 2 * this.zoom ); var cx = ( this.right + this.left ) / 2; var cy = ( this.top + this.bottom ) / 2; var left = cx - dx; var right = cx + dx; var top = cy + dy; var bottom = cy - dy; if ( this.view !== null && this.view.enabled ) { var scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom; var scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom; left += scaleW * this.view.offsetX; right = left + scaleW * this.view.width; top -= scaleH * this.view.offsetY; bottom = top - scaleH * this.view.height; } this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far ); this.projectionMatrixInverse.getInverse( this.projectionMatrix ); }, toJSON: function ( meta ) { var data = Object3D.prototype.toJSON.call( this, meta ); data.object.zoom = this.zoom; data.object.left = this.left; data.object.right = this.right; data.object.top = this.top; data.object.bottom = this.bottom; data.object.near = this.near; data.object.far = this.far; if ( this.view !== null ) { data.object.view = Object.assign( {}, this.view ); } return data; } } ); /** * @author mrdoob / http://mrdoob.com/ */ function DirectionalLightShadow() { LightShadow.call( this, new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) ); } DirectionalLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), { constructor: DirectionalLightShadow, isDirectionalLightShadow: true, updateMatrices: function ( light ) { LightShadow.prototype.updateMatrices.call( this, light ); } } ); /** * @author mrdoob / http://mrdoob.com/ * @author alteredq / http://alteredqualia.com/ */ function DirectionalLight( color, intensity ) { Light.call( this, color, intensity ); this.type = 'DirectionalLight'; this.position.copy( Object3D.DefaultUp ); this.updateMatrix(); this.target = new Object3D(); this.shadow = new DirectionalLightShadow(); } DirectionalLight.prototype = Object.assign( Object.create( Light.prototype ), { constructor: DirectionalLight, isDirectionalLight: true, copy: function ( source ) { Light.prototype.copy.call( this, source ); this.target = source.target.clone(); this.shadow = source.shadow.clone(); return this; } } ); /** * @author mrdoob / http://mrdoob.com/ */ function AmbientLight( color, intensity ) { Light.call( this, color, intensity ); this.type = 'AmbientLight'; this.castShadow = undefined; } AmbientLight.prototype = Object.assign( Object.create( Light.prototype ), { constructor: AmbientLight, isAmbientLight: true } ); /** * @author abelnation / http://github.com/abelnation */ function RectAreaLight( color, intensity, width, height ) { Light.call( this, color, intensity ); this.type = 'RectAreaLight'; this.width = ( width !== undefined ) ? width : 10; this.height = ( height !== undefined ) ? height : 10; } RectAreaLight.prototype = Object.assign( Object.create( Light.prototype ), { constructor: RectAreaLight, isRectAreaLight: true, copy: function ( source ) { Light.prototype.copy.call( this, source ); this.width = source.width; this.height = source.height; return this; }, toJSON: function ( meta ) { var data = Light.prototype.toJSON.call( this, meta ); data.object.width = this.width; data.object.height = this.height; return data; } } ); /** * @author mrdoob / http://mrdoob.com/ */ function MaterialLoader( manager ) { Loader.call( this, manager ); this.textures = {}; } MaterialLoader.prototype = Object.assign( Object.create( Loader.prototype ), { constructor: MaterialLoader, load: function ( url, onLoad, onProgress, onError ) { var scope = this; var loader = new FileLoader( scope.manager ); loader.setPath( scope.path ); loader.load( url, function ( text ) { onLoad( scope.parse( JSON.parse( text ) ) ); }, onProgress, onError ); }, parse: function ( json ) { var textures = this.textures; function getTexture( name ) { if ( textures[ name ] === undefined ) { console.warn( 'THREE.MaterialLoader: Undefined texture', name ); } return textures[ name ]; } var material = new Materials[ json.type ](); if ( json.uuid !== undefined ) { material.uuid = json.uuid; } if ( json.name !== undefined ) { material.name = json.name; } if ( json.color !== undefined ) { material.color.setHex( json.color ); } if ( json.roughness !== undefined ) { material.roughness = json.roughness; } if ( json.metalness !== undefined ) { material.metalness = json.metalness; } if ( json.sheen !== undefined ) { material.sheen = new Color().setHex( json.sheen ); } if ( json.emissive !== undefined ) { material.emissive.setHex( json.emissive ); } if ( json.specular !== undefined ) { material.specular.setHex( json.specular ); } if ( json.shininess !== undefined ) { material.shininess = json.shininess; } if ( json.clearcoat !== undefined ) { material.clearcoat = json.clearcoat; } if ( json.clearcoatRoughness !== undefined ) { material.clearcoatRoughness = json.clearcoatRoughness; } if ( json.vertexColors !== undefined ) { material.vertexColors = json.vertexColors; } if ( json.fog !== undefined ) { material.fog = json.fog; } if ( json.flatShading !== undefined ) { material.flatShading = json.flatShading; } if ( json.blending !== undefined ) { material.blending = json.blending; } if ( json.combine !== undefined ) { material.combine = json.combine; } if ( json.side !== undefined ) { material.side = json.side; } if ( json.opacity !== undefined ) { material.opacity = json.opacity; } if ( json.transparent !== undefined ) { material.transparent = json.transparent; } if ( json.alphaTest !== undefined ) { material.alphaTest = json.alphaTest; } if ( json.depthTest !== undefined ) { material.depthTest = json.depthTest; } if ( json.depthWrite !== undefined ) { material.depthWrite = json.depthWrite; } if ( json.colorWrite !== undefined ) { material.colorWrite = json.colorWrite; } if ( json.stencilWrite !== undefined ) { material.stencilWrite = json.stencilWrite; } if ( json.stencilWriteMask !== undefined ) { material.stencilWriteMask = json.stencilWriteMask; } if ( json.stencilFunc !== undefined ) { material.stencilFunc = json.stencilFunc; } if ( json.stencilRef !== undefined ) { material.stencilRef = json.stencilRef; } if ( json.stencilFuncMask !== undefined ) { material.stencilFuncMask = json.stencilFuncMask; } if ( json.stencilFail !== undefined ) { material.stencilFail = json.stencilFail; } if ( json.stencilZFail !== undefined ) { material.stencilZFail = json.stencilZFail; } if ( json.stencilZPass !== undefined ) { material.stencilZPass = json.stencilZPass; } if ( json.wireframe !== undefined ) { material.wireframe = json.wireframe; } if ( json.wireframeLinewidth !== undefined ) { material.wireframeLinewidth = json.wireframeLinewidth; } if ( json.wireframeLinecap !== undefined ) { material.wireframeLinecap = json.wireframeLinecap; } if ( json.wireframeLinejoin !== undefined ) { material.wireframeLinejoin = json.wireframeLinejoin; } if ( json.rotation !== undefined ) { material.rotation = json.rotation; } if ( json.linewidth !== 1 ) { material.linewidth = json.linewidth; } if ( json.dashSize !== undefined ) { material.dashSize = json.dashSize; } if ( json.gapSize !== undefined ) { material.gapSize = json.gapSize; } if ( json.scale !== undefined ) { material.scale = json.scale; } if ( json.polygonOffset !== undefined ) { material.polygonOffset = json.polygonOffset; } if ( json.polygonOffsetFactor !== undefined ) { material.polygonOffsetFactor = json.polygonOffsetFactor; } if ( json.polygonOffsetUnits !== undefined ) { material.polygonOffsetUnits = json.polygonOffsetUnits; } if ( json.skinning !== undefined ) { material.skinning = json.skinning; } if ( json.morphTargets !== undefined ) { material.morphTargets = json.morphTargets; } if ( json.morphNormals !== undefined ) { material.morphNormals = json.morphNormals; } if ( json.dithering !== undefined ) { material.dithering = json.dithering; } if ( json.visible !== undefined ) { material.visible = json.visible; } if ( json.toneMapped !== undefined ) { material.toneMapped = json.toneMapped; } if ( json.userData !== undefined ) { material.userData = json.userData; } // Shader Material if ( json.uniforms !== undefined ) { for ( var name in json.uniforms ) { var uniform = json.uniforms[ name ]; material.uniforms[ name ] = {}; switch ( uniform.type ) { case 't': material.uniforms[ name ].value = getTexture( uniform.value ); break; case 'c': material.uniforms[ name ].value = new Color().setHex( uniform.value ); break; case 'v2': material.uniforms[ name ].value = new Vector2().fromArray( uniform.value ); break; case 'v3': material.uniforms[ name ].value = new Vector3().fromArray( uniform.value ); break; case 'v4': material.uniforms[ name ].value = new Vector4().fromArray( uniform.value ); break; case 'm3': material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value ); case 'm4': material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value ); break; default: material.uniforms[ name ].value = uniform.value; } } } if ( json.defines !== undefined ) { material.defines = json.defines; } if ( json.vertexShader !== undefined ) { material.vertexShader = json.vertexShader; } if ( json.fragmentShader !== undefined ) { material.fragmentShader = json.fragmentShader; } if ( json.extensions !== undefined ) { for ( var key in json.extensions ) { material.extensions[ key ] = json.extensions[ key ]; } } // Deprecated if ( json.shading !== undefined ) { material.flatShading = json.shading === 1; } // THREE.FlatShading // for PointsMaterial if ( json.size !== undefined ) { material.size = json.size; } if ( json.sizeAttenuation !== undefined ) { material.sizeAttenuation = json.sizeAttenuation; } // maps if ( json.map !== undefined ) { material.map = getTexture( json.map ); } if ( json.matcap !== undefined ) { material.matcap = getTexture( json.matcap ); } if ( json.alphaMap !== undefined ) { material.alphaMap = getTexture( json.alphaMap ); material.transparent = true; } if ( json.bumpMap !== undefined ) { material.bumpMap = getTexture( json.bumpMap ); } if ( json.bumpScale !== undefined ) { material.bumpScale = json.bumpScale; } if ( json.normalMap !== undefined ) { material.normalMap = getTexture( json.normalMap ); } if ( json.normalMapType !== undefined ) { material.normalMapType = json.normalMapType; } if ( json.normalScale !== undefined ) { var normalScale = json.normalScale; if ( Array.isArray( normalScale ) === false ) { // Blender exporter used to export a scalar. See #7459 normalScale = [ normalScale, normalScale ]; } material.normalScale = new Vector2().fromArray( normalScale ); } if ( json.displacementMap !== undefined ) { material.displacementMap = getTexture( json.displacementMap ); } if ( json.displacementScale !== undefined ) { material.displacementScale = json.displacementScale; } if ( json.displacementBias !== undefined ) { material.displacementBias = json.displacementBias; } if ( json.roughnessMap !== undefined ) { material.roughnessMap = getTexture( json.roughnessMap ); } if ( json.metalnessMap !== undefined ) { material.metalnessMap = getTexture( json.metalnessMap ); } if ( json.emissiveMap !== undefined ) { material.emissiveMap = getTexture( json.emissiveMap ); } if ( json.emissiveIntensity !== undefined ) { material.emissiveIntensity = json.emissiveIntensity; } if ( json.specularMap !== undefined ) { material.specularMap = getTexture( json.specularMap ); } if ( json.envMap !== undefined ) { material.envMap = getTexture( json.envMap ); } if ( json.envMapIntensity !== undefined ) { material.envMapIntensity = json.envMapIntensity; } if ( json.reflectivity !== undefined ) { material.reflectivity = json.reflectivity; } if ( json.refractionRatio !== undefined ) { material.refractionRatio = json.refractionRatio; } if ( json.lightMap !== undefined ) { material.lightMap = getTexture( json.lightMap ); } if ( json.lightMapIntensity !== undefined ) { material.lightMapIntensity = json.lightMapIntensity; } if ( json.aoMap !== undefined ) { material.aoMap = getTexture( json.aoMap ); } if ( json.aoMapIntensity !== undefined ) { material.aoMapIntensity = json.aoMapIntensity; } if ( json.gradientMap !== undefined ) { material.gradientMap = getTexture( json.gradientMap ); } if ( json.clearcoatNormalMap !== undefined ) { material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap ); } if ( json.clearcoatNormalScale !== undefined ) { material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale ); } return material; }, setTextures: function ( value ) { this.textures = value; return this; } } ); /** * @author Don McCurdy / https://www.donmccurdy.com */ var LoaderUtils = { decodeText: function ( array ) { if ( typeof TextDecoder !== 'undefined' ) { return new TextDecoder().decode( array ); } // Avoid the String.fromCharCode.apply(null, array) shortcut, which // throws a "maximum call stack size exceeded" error for large arrays. var s = ''; for ( var i = 0, il = array.length; i < il; i ++ ) { // Implicitly assumes little-endian. s += String.fromCharCode( array[ i ] ); } try { // merges multi-byte utf-8 characters. return decodeURIComponent( escape( s ) ); } catch ( e ) { // see #16358 return s; } }, extractUrlBase: function ( url ) { var index = url.lastIndexOf( '/' ); if ( index === - 1 ) { return './'; } return url.substr( 0, index + 1 ); } }; /** * @author benaadams / https://twitter.com/ben_a_adams */ function InstancedBufferGeometry() { BufferGeometry.call( this ); this.type = 'InstancedBufferGeometry'; this.maxInstancedCount = undefined; } InstancedBufferGeometry.prototype = Object.assign( Object.create( BufferGeometry.prototype ), { constructor: InstancedBufferGeometry, isInstancedBufferGeometry: true, copy: function ( source ) { BufferGeometry.prototype.copy.call( this, source ); this.maxInstancedCount = source.maxInstancedCount; return this; }, clone: function () { return new this.constructor().copy( this ); }, toJSON: function () { var data = BufferGeometry.prototype.toJSON.call( this ); data.maxInstancedCount = this.maxInstancedCount; data.isInstancedBufferGeometry = true; return data; } } ); /** * @author benaadams / https://twitter.com/ben_a_adams */ function InstancedBufferAttribute( array, itemSize, normalized, meshPerAttribute ) { if ( typeof ( normalized ) === 'number' ) { meshPerAttribute = normalized; normalized = false; console.error( 'THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.' ); } BufferAttribute.call( this, array, itemSize, normalized ); this.meshPerAttribute = meshPerAttribute || 1; } InstancedBufferAttribute.prototype = Object.assign( Object.create( BufferAttribute.prototype ), { constructor: InstancedBufferAttribute, isInstancedBufferAttribute: true, copy: function ( source ) { BufferAttribute.prototype.copy.call( this, source ); this.meshPerAttribute = source.meshPerAttribute; return this; }, toJSON: function () { var data = BufferAttribute.prototype.toJSON.call( this ); data.meshPerAttribute = this.meshPerAttribute; data.isInstancedBufferAttribute = true; return data; } } ); /** * @author mrdoob / http://mrdoob.com/ */ function BufferGeometryLoader( manager ) { Loader.call( this, manager ); } BufferGeometryLoader.prototype = Object.assign( Object.create( Loader.prototype ), { constructor: BufferGeometryLoader, load: function ( url, onLoad, onProgress, onError ) { var scope = this; var loader = new FileLoader( scope.manager ); loader.setPath( scope.path ); loader.load( url, function ( text ) { onLoad( scope.parse( JSON.parse( text ) ) ); }, onProgress, onError ); }, parse: function ( json ) { var geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry(); var index = json.data.index; if ( index !== undefined ) { var typedArray = new TYPED_ARRAYS[ index.type ]( index.array ); geometry.setIndex( new BufferAttribute( typedArray, 1 ) ); } var attributes = json.data.attributes; for ( var key in attributes ) { var attribute = attributes[ key ]; var typedArray = new TYPED_ARRAYS[ attribute.type ]( attribute.array ); var bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute; var bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized ); if ( attribute.name !== undefined ) { bufferAttribute.name = attribute.name; } geometry.setAttribute( key, bufferAttribute ); } var morphAttributes = json.data.morphAttributes; if ( morphAttributes ) { for ( var key in morphAttributes ) { var attributeArray = morphAttributes[ key ]; var array = []; for ( var i = 0, il = attributeArray.length; i < il; i ++ ) { var attribute = attributeArray[ i ]; var typedArray = new TYPED_ARRAYS[ attribute.type ]( attribute.array ); var bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized ); if ( attribute.name !== undefined ) { bufferAttribute.name = attribute.name; } array.push( bufferAttribute ); } geometry.morphAttributes[ key ] = array; } } var morphTargetsRelative = json.data.morphTargetsRelative; if ( morphTargetsRelative ) { geometry.morphTargetsRelative = true; } var groups = json.data.groups || json.data.drawcalls || json.data.offsets; if ( groups !== undefined ) { for ( var i = 0, n = groups.length; i !== n; ++ i ) { var group = groups[ i ]; geometry.addGroup( group.start, group.count, group.materialIndex ); } } var boundingSphere = json.data.boundingSphere; if ( boundingSphere !== undefined ) { var center = new Vector3(); if ( boundingSphere.center !== undefined ) { center.fromArray( boundingSphere.center ); } geometry.boundingSphere = new Sphere( center, boundingSphere.radius ); } if ( json.name ) { geometry.name = json.name; } if ( json.userData ) { geometry.userData = json.userData; } return geometry; } } ); var TYPED_ARRAYS = { Int8Array: Int8Array, Uint8Array: Uint8Array, // Workaround for IE11 pre KB2929437. See #11440 Uint8ClampedArray: typeof Uint8ClampedArray !== 'undefined' ? Uint8ClampedArray : Uint8Array, Int16Array: Int16Array, Uint16Array: Uint16Array, Int32Array: Int32Array, Uint32Array: Uint32Array, Float32Array: Float32Array, Float64Array: Float64Array }; /** * @author mrdoob / http://mrdoob.com/ */ function ObjectLoader( manager ) { Loader.call( this, manager ); } ObjectLoader.prototype = Object.assign( Object.create( Loader.prototype ), { constructor: ObjectLoader, load: function ( url, onLoad, onProgress, onError ) { var scope = this; var path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path; this.resourcePath = this.resourcePath || path; var loader = new FileLoader( scope.manager ); loader.setPath( this.path ); loader.load( url, function ( text ) { var json = null; try { json = JSON.parse( text ); } catch ( error ) { if ( onError !== undefined ) { onError( error ); } console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message ); return; } var metadata = json.metadata; if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) { console.error( 'THREE.ObjectLoader: Can\'t load ' + url ); return; } scope.parse( json, onLoad ); }, onProgress, onError ); }, parse: function ( json, onLoad ) { var shapes = this.parseShape( json.shapes ); var geometries = this.parseGeometries( json.geometries, shapes ); var images = this.parseImages( json.images, function () { if ( onLoad !== undefined ) { onLoad( object ); } } ); var textures = this.parseTextures( json.textures, images ); var materials = this.parseMaterials( json.materials, textures ); var object = this.parseObject( json.object, geometries, materials ); if ( json.animations ) { object.animations = this.parseAnimations( json.animations ); } if ( json.images === undefined || json.images.length === 0 ) { if ( onLoad !== undefined ) { onLoad( object ); } } return object; }, parseShape: function ( json ) { var shapes = {}; if ( json !== undefined ) { for ( var i = 0, l = json.length; i < l; i ++ ) { var shape = new Shape().fromJSON( json[ i ] ); shapes[ shape.uuid ] = shape; } } return shapes; }, parseGeometries: function ( json, shapes ) { var geometries = {}; if ( json !== undefined ) { var bufferGeometryLoader = new BufferGeometryLoader(); for ( var i = 0, l = json.length; i < l; i ++ ) { var geometry; var data = json[ i ]; switch ( data.type ) { case 'PlaneGeometry': case 'PlaneBufferGeometry': geometry = new Geometries[ data.type ]( data.width, data.height, data.widthSegments, data.heightSegments ); break; case 'BoxGeometry': case 'BoxBufferGeometry': case 'CubeGeometry': // backwards compatible geometry = new Geometries[ data.type ]( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments ); break; case 'CircleGeometry': case 'CircleBufferGeometry': geometry = new Geometries[ data.type ]( data.radius, data.segments, data.thetaStart, data.thetaLength ); break; case 'CylinderGeometry': case 'CylinderBufferGeometry': geometry = new Geometries[ data.type ]( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength ); break; case 'ConeGeometry': case 'ConeBufferGeometry': geometry = new Geometries[ data.type ]( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength ); break; case 'SphereGeometry': case 'SphereBufferGeometry': geometry = new Geometries[ data.type ]( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength ); break; case 'DodecahedronGeometry': case 'DodecahedronBufferGeometry': case 'IcosahedronGeometry': case 'IcosahedronBufferGeometry': case 'OctahedronGeometry': case 'OctahedronBufferGeometry': case 'TetrahedronGeometry': case 'TetrahedronBufferGeometry': geometry = new Geometries[ data.type ]( data.radius, data.detail ); break; case 'RingGeometry': case 'RingBufferGeometry': geometry = new Geometries[ data.type ]( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength ); break; case 'TorusGeometry': case 'TorusBufferGeometry': geometry = new Geometries[ data.type ]( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc ); break; case 'TorusKnotGeometry': case 'TorusKnotBufferGeometry': geometry = new Geometries[ data.type ]( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q ); break; case 'TubeGeometry': case 'TubeBufferGeometry': // This only works for built-in curves (e.g. CatmullRomCurve3). // User defined curves or instances of CurvePath will not be deserialized. geometry = new Geometries[ data.type ]( new Curves[ data.path.type ]().fromJSON( data.path ), data.tubularSegments, data.radius, data.radialSegments, data.closed ); break; case 'LatheGeometry': case 'LatheBufferGeometry': geometry = new Geometries[ data.type ]( data.points, data.segments, data.phiStart, data.phiLength ); break; case 'PolyhedronGeometry': case 'PolyhedronBufferGeometry': geometry = new Geometries[ data.type ]( data.vertices, data.indices, data.radius, data.details ); break; case 'ShapeGeometry': case 'ShapeBufferGeometry': var geometryShapes = []; for ( var j = 0, jl = data.shapes.length; j < jl; j ++ ) { var shape = shapes[ data.shapes[ j ] ]; geometryShapes.push( shape ); } geometry = new Geometries[ data.type ]( geometryShapes, data.curveSegments ); break; case 'ExtrudeGeometry': case 'ExtrudeBufferGeometry': var geometryShapes = []; for ( var j = 0, jl = data.shapes.length; j < jl; j ++ ) { var shape = shapes[ data.shapes[ j ] ]; geometryShapes.push( shape ); } var extrudePath = data.options.extrudePath; if ( extrudePath !== undefined ) { data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath ); } geometry = new Geometries[ data.type ]( geometryShapes, data.options ); break; case 'BufferGeometry': case 'InstancedBufferGeometry': geometry = bufferGeometryLoader.parse( data ); break; case 'Geometry': if ( 'THREE' in window && 'LegacyJSONLoader' in THREE ) { var geometryLoader = new THREE.LegacyJSONLoader(); geometry = geometryLoader.parse( data, this.resourcePath ).geometry; } else { console.error( 'THREE.ObjectLoader: You have to import LegacyJSONLoader in order load geometry data of type "Geometry".' ); } break; default: console.warn( 'THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"' ); continue; } geometry.uuid = data.uuid; if ( data.name !== undefined ) { geometry.name = data.name; } if ( geometry.isBufferGeometry === true && data.userData !== undefined ) { geometry.userData = data.userData; } geometries[ data.uuid ] = geometry; } } return geometries; }, parseMaterials: function ( json, textures ) { var cache = {}; // MultiMaterial var materials = {}; if ( json !== undefined ) { var loader = new MaterialLoader(); loader.setTextures( textures ); for ( var i = 0, l = json.length; i < l; i ++ ) { var data = json[ i ]; if ( data.type === 'MultiMaterial' ) { // Deprecated var array = []; for ( var j = 0; j < data.materials.length; j ++ ) { var material = data.materials[ j ]; if ( cache[ material.uuid ] === undefined ) { cache[ material.uuid ] = loader.parse( material ); } array.push( cache[ material.uuid ] ); } materials[ data.uuid ] = array; } else { if ( cache[ data.uuid ] === undefined ) { cache[ data.uuid ] = loader.parse( data ); } materials[ data.uuid ] = cache[ data.uuid ]; } } } return materials; }, parseAnimations: function ( json ) { var animations = []; for ( var i = 0; i < json.length; i ++ ) { var data = json[ i ]; var clip = AnimationClip.parse( data ); if ( data.uuid !== undefined ) { clip.uuid = data.uuid; } animations.push( clip ); } return animations; }, parseImages: function ( json, onLoad ) { var scope = this; var images = {}; function loadImage( url ) { scope.manager.itemStart( url ); return loader.load( url, function () { scope.manager.itemEnd( url ); }, undefined, function () { scope.manager.itemError( url ); scope.manager.itemEnd( url ); } ); } if ( json !== undefined && json.length > 0 ) { var manager = new LoadingManager( onLoad ); var loader = new ImageLoader( manager ); loader.setCrossOrigin( this.crossOrigin ); for ( var i = 0, il = json.length; i < il; i ++ ) { var image = json[ i ]; var url = image.url; if ( Array.isArray( url ) ) { // load array of images e.g CubeTexture images[ image.uuid ] = []; for ( var j = 0, jl = url.length; j < jl; j ++ ) { var currentUrl = url[ j ]; var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( currentUrl ) ? currentUrl : scope.resourcePath + currentUrl; images[ image.uuid ].push( loadImage( path ) ); } } else { // load single image var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( image.url ) ? image.url : scope.resourcePath + image.url; images[ image.uuid ] = loadImage( path ); } } } return images; }, parseTextures: function ( json, images ) { function parseConstant( value, type ) { if ( typeof value === 'number' ) { return value; } console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value ); return type[ value ]; } var textures = {}; if ( json !== undefined ) { for ( var i = 0, l = json.length; i < l; i ++ ) { var data = json[ i ]; if ( data.image === undefined ) { console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid ); } if ( images[ data.image ] === undefined ) { console.warn( 'THREE.ObjectLoader: Undefined image', data.image ); } var texture; if ( Array.isArray( images[ data.image ] ) ) { texture = new CubeTexture( images[ data.image ] ); } else { texture = new Texture( images[ data.image ] ); } texture.needsUpdate = true; texture.uuid = data.uuid; if ( data.name !== undefined ) { texture.name = data.name; } if ( data.mapping !== undefined ) { texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING ); } if ( data.offset !== undefined ) { texture.offset.fromArray( data.offset ); } if ( data.repeat !== undefined ) { texture.repeat.fromArray( data.repeat ); } if ( data.center !== undefined ) { texture.center.fromArray( data.center ); } if ( data.rotation !== undefined ) { texture.rotation = data.rotation; } if ( data.wrap !== undefined ) { texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING ); texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING ); } if ( data.format !== undefined ) { texture.format = data.format; } if ( data.type !== undefined ) { texture.type = data.type; } if ( data.encoding !== undefined ) { texture.encoding = data.encoding; } if ( data.minFilter !== undefined ) { texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER ); } if ( data.magFilter !== undefined ) { texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER ); } if ( data.anisotropy !== undefined ) { texture.anisotropy = data.anisotropy; } if ( data.flipY !== undefined ) { texture.flipY = data.flipY; } if ( data.premultiplyAlpha !== undefined ) { texture.premultiplyAlpha = data.premultiplyAlpha; } if ( data.unpackAlignment !== undefined ) { texture.unpackAlignment = data.unpackAlignment; } textures[ data.uuid ] = texture; } } return textures; }, parseObject: function ( data, geometries, materials ) { var object; function getGeometry( name ) { if ( geometries[ name ] === undefined ) { console.warn( 'THREE.ObjectLoader: Undefined geometry', name ); } return geometries[ name ]; } function getMaterial( name ) { if ( name === undefined ) { return undefined; } if ( Array.isArray( name ) ) { var array = []; for ( var i = 0, l = name.length; i < l; i ++ ) { var uuid = name[ i ]; if ( materials[ uuid ] === undefined ) { console.warn( 'THREE.ObjectLoader: Undefined material', uuid ); } array.push( materials[ uuid ] ); } return array; } if ( materials[ name ] === undefined ) { console.warn( 'THREE.ObjectLoader: Undefined material', name ); } return materials[ name ]; } switch ( data.type ) { case 'Scene': object = new Scene(); if ( data.background !== undefined ) { if ( Number.isInteger( data.background ) ) { object.background = new Color( data.background ); } } if ( data.fog !== undefined ) { if ( data.fog.type === 'Fog' ) { object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far ); } else if ( data.fog.type === 'FogExp2' ) { object.fog = new FogExp2( data.fog.color, data.fog.density ); } } break; case 'PerspectiveCamera': object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far ); if ( data.focus !== undefined ) { object.focus = data.focus; } if ( data.zoom !== undefined ) { object.zoom = data.zoom; } if ( data.filmGauge !== undefined ) { object.filmGauge = data.filmGauge; } if ( data.filmOffset !== undefined ) { object.filmOffset = data.filmOffset; } if ( data.view !== undefined ) { object.view = Object.assign( {}, data.view ); } break; case 'OrthographicCamera': object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far ); if ( data.zoom !== undefined ) { object.zoom = data.zoom; } if ( data.view !== undefined ) { object.view = Object.assign( {}, data.view ); } break; case 'AmbientLight': object = new AmbientLight( data.color, data.intensity ); break; case 'DirectionalLight': object = new DirectionalLight( data.color, data.intensity ); break; case 'PointLight': object = new PointLight( data.color, data.intensity, data.distance, data.decay ); break; case 'RectAreaLight': object = new RectAreaLight( data.color, data.intensity, data.width, data.height ); break; case 'SpotLight': object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay ); break; case 'HemisphereLight': object = new HemisphereLight( data.color, data.groundColor, data.intensity ); break; case 'SkinnedMesh': console.warn( 'THREE.ObjectLoader.parseObject() does not support SkinnedMesh yet.' ); case 'Mesh': var geometry = getGeometry( data.geometry ); var material = getMaterial( data.material ); if ( geometry.bones && geometry.bones.length > 0 ) { object = new SkinnedMesh( geometry, material ); } else { object = new Mesh( geometry, material ); } break; case 'InstancedMesh': var geometry = getGeometry( data.geometry ); var material = getMaterial( data.material ); var count = data.count; var instanceMatrix = data.instanceMatrix; object = new InstancedMesh( geometry, material, count ); object.instanceMatrix = new BufferAttribute( new Float32Array( instanceMatrix.array ), 16 ); break; case 'LOD': object = new LOD(); break; case 'Line': object = new Line( getGeometry( data.geometry ), getMaterial( data.material ), data.mode ); break; case 'LineLoop': object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) ); break; case 'LineSegments': object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) ); break; case 'PointCloud': case 'Points': object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) ); break; case 'Sprite': object = new Sprite( getMaterial( data.material ) ); break; case 'Group': object = new Group(); break; default: object = new Object3D(); } object.uuid = data.uuid; if ( data.name !== undefined ) { object.name = data.name; } if ( data.matrix !== undefined ) { object.matrix.fromArray( data.matrix ); if ( data.matrixAutoUpdate !== undefined ) { object.matrixAutoUpdate = data.matrixAutoUpdate; } if ( object.matrixAutoUpdate ) { object.matrix.decompose( object.position, object.quaternion, object.scale ); } } else { if ( data.position !== undefined ) { object.position.fromArray( data.position ); } if ( data.rotation !== undefined ) { object.rotation.fromArray( data.rotation ); } if ( data.quaternion !== undefined ) { object.quaternion.fromArray( data.quaternion ); } if ( data.scale !== undefined ) { object.scale.fromArray( data.scale ); } } if ( data.castShadow !== undefined ) { object.castShadow = data.castShadow; } if ( data.receiveShadow !== undefined ) { object.receiveShadow = data.receiveShadow; } if ( data.shadow ) { if ( data.shadow.bias !== undefined ) { object.shadow.bias = data.shadow.bias; } if ( data.shadow.radius !== undefined ) { object.shadow.radius = data.shadow.radius; } if ( data.shadow.mapSize !== undefined ) { object.shadow.mapSize.fromArray( data.shadow.mapSize ); } if ( data.shadow.camera !== undefined ) { object.shadow.camera = this.parseObject( data.shadow.camera ); } } if ( data.visible !== undefined ) { object.visible = data.visible; } if ( data.frustumCulled !== undefined ) { object.frustumCulled = data.frustumCulled; } if ( data.renderOrder !== undefined ) { object.renderOrder = data.renderOrder; } if ( data.userData !== undefined ) { object.userData = data.userData; } if ( data.layers !== undefined ) { object.layers.mask = data.layers; } if ( data.children !== undefined ) { var children = data.children; for ( var i = 0; i < children.length; i ++ ) { object.add( this.parseObject( children[ i ], geometries, materials ) ); } } if ( data.type === 'LOD' ) { if ( data.autoUpdate !== undefined ) { object.autoUpdate = data.autoUpdate; } var levels = data.levels; for ( var l = 0; l < levels.length; l ++ ) { var level = levels[ l ]; var child = object.getObjectByProperty( 'uuid', level.object ); if ( child !== undefined ) { object.addLevel( child, level.distance ); } } } return object; } } ); var TEXTURE_MAPPING = { UVMapping: UVMapping, CubeReflectionMapping: CubeReflectionMapping, CubeRefractionMapping: CubeRefractionMapping, EquirectangularReflectionMapping: EquirectangularReflectionMapping, EquirectangularRefractionMapping: EquirectangularRefractionMapping, SphericalReflectionMapping: SphericalReflectionMapping, CubeUVReflectionMapping: CubeUVReflectionMapping, CubeUVRefractionMapping: CubeUVRefractionMapping }; var TEXTURE_WRAPPING = { RepeatWrapping: RepeatWrapping, ClampToEdgeWrapping: ClampToEdgeWrapping, MirroredRepeatWrapping: MirroredRepeatWrapping }; var TEXTURE_FILTER = { NearestFilter: NearestFilter, NearestMipmapNearestFilter: NearestMipmapNearestFilter, NearestMipmapLinearFilter: NearestMipmapLinearFilter, LinearFilter: LinearFilter, LinearMipmapNearestFilter: LinearMipmapNearestFilter, LinearMipmapLinearFilter: LinearMipmapLinearFilter }; /** * @author thespite / http://clicktorelease.com/ */ function ImageBitmapLoader( manager ) { if ( typeof createImageBitmap === 'undefined' ) { console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' ); } if ( typeof fetch === 'undefined' ) { console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' ); } Loader.call( this, manager ); this.options = undefined; } ImageBitmapLoader.prototype = Object.assign( Object.create( Loader.prototype ), { constructor: ImageBitmapLoader, setOptions: function setOptions( options ) { this.options = options; return this; }, load: function ( url, onLoad, onProgress, onError ) { if ( url === undefined ) { url = ''; } if ( this.path !== undefined ) { url = this.path + url; } url = this.manager.resolveURL( url ); var scope = this; var cached = Cache.get( url ); if ( cached !== undefined ) { scope.manager.itemStart( url ); setTimeout( function () { if ( onLoad ) { onLoad( cached ); } scope.manager.itemEnd( url ); }, 0 ); return cached; } fetch( url ).then( function ( res ) { return res.blob(); } ).then( function ( blob ) { if ( scope.options === undefined ) { // Workaround for FireFox. It causes an error if you pass options. return createImageBitmap( blob ); } else { return createImageBitmap( blob, scope.options ); } } ).then( function ( imageBitmap ) { Cache.add( url, imageBitmap ); if ( onLoad ) { onLoad( imageBitmap ); } scope.manager.itemEnd( url ); } ).catch( function ( e ) { if ( onError ) { onError( e ); } scope.manager.itemError( url ); scope.manager.itemEnd( url ); } ); scope.manager.itemStart( url ); } } ); /** * @author zz85 / http://www.lab4games.net/zz85/blog * minimal class for proxing functions to Path. Replaces old "extractSubpaths()" **/ function ShapePath() { this.type = 'ShapePath'; this.color = new Color(); this.subPaths = []; this.currentPath = null; } Object.assign( ShapePath.prototype, { moveTo: function ( x, y ) { this.currentPath = new Path(); this.subPaths.push( this.currentPath ); this.currentPath.moveTo( x, y ); return this; }, lineTo: function ( x, y ) { this.currentPath.lineTo( x, y ); return this; }, quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) { this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY ); return this; }, bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) { this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ); return this; }, splineThru: function ( pts ) { this.currentPath.splineThru( pts ); return this; }, toShapes: function ( isCCW, noHoles ) { function toShapesNoHoles( inSubpaths ) { var shapes = []; for ( var i = 0, l = inSubpaths.length; i < l; i ++ ) { var tmpPath = inSubpaths[ i ]; var tmpShape = new Shape(); tmpShape.curves = tmpPath.curves; shapes.push( tmpShape ); } return shapes; } function isPointInsidePolygon( inPt, inPolygon ) { var polyLen = inPolygon.length; // inPt on polygon contour => immediate success or // toggling of inside/outside at every single! intersection point of an edge // with the horizontal line through inPt, left of inPt // not counting lowerY endpoints of edges and whole edges on that line var inside = false; for ( var p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) { var edgeLowPt = inPolygon[ p ]; var edgeHighPt = inPolygon[ q ]; var edgeDx = edgeHighPt.x - edgeLowPt.x; var edgeDy = edgeHighPt.y - edgeLowPt.y; if ( Math.abs( edgeDy ) > Number.EPSILON ) { // not parallel if ( edgeDy < 0 ) { edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx; edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy; } if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) { continue; } if ( inPt.y === edgeLowPt.y ) { if ( inPt.x === edgeLowPt.x ) { return true; } // inPt is on contour ? // continue; // no intersection or edgeLowPt => doesn't count !!! } else { var perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y ); if ( perpEdge === 0 ) { return true; } // inPt is on contour ? if ( perpEdge < 0 ) { continue; } inside = ! inside; // true intersection left of inPt } } else { // parallel or collinear if ( inPt.y !== edgeLowPt.y ) { continue; } // parallel // edge lies on the same horizontal line as inPt if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) || ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) { return true; } // inPt: Point on contour ! // continue; } } return inside; } var isClockWise = ShapeUtils.isClockWise; var subPaths = this.subPaths; if ( subPaths.length === 0 ) { return []; } if ( noHoles === true ) { return toShapesNoHoles( subPaths ); } var solid, tmpPath, tmpShape, shapes = []; if ( subPaths.length === 1 ) { tmpPath = subPaths[ 0 ]; tmpShape = new Shape(); tmpShape.curves = tmpPath.curves; shapes.push( tmpShape ); return shapes; } var holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() ); holesFirst = isCCW ? ! holesFirst : holesFirst; // console.log("Holes first", holesFirst); var betterShapeHoles = []; var newShapes = []; var newShapeHoles = []; var mainIdx = 0; var tmpPoints; newShapes[ mainIdx ] = undefined; newShapeHoles[ mainIdx ] = []; for ( var i = 0, l = subPaths.length; i < l; i ++ ) { tmpPath = subPaths[ i ]; tmpPoints = tmpPath.getPoints(); solid = isClockWise( tmpPoints ); solid = isCCW ? ! solid : solid; if ( solid ) { if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) { mainIdx ++; } newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints }; newShapes[ mainIdx ].s.curves = tmpPath.curves; if ( holesFirst ) { mainIdx ++; } newShapeHoles[ mainIdx ] = []; //console.log('cw', i); } else { newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } ); //console.log('ccw', i); } } // only Holes? -> probably all Shapes with wrong orientation if ( ! newShapes[ 0 ] ) { return toShapesNoHoles( subPaths ); } if ( newShapes.length > 1 ) { var ambiguous = false; var toChange = []; for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) { betterShapeHoles[ sIdx ] = []; } for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) { var sho = newShapeHoles[ sIdx ]; for ( var hIdx = 0; hIdx < sho.length; hIdx ++ ) { var ho = sho[ hIdx ]; var hole_unassigned = true; for ( var s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) { if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) { if ( sIdx !== s2Idx ) { toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } ); } if ( hole_unassigned ) { hole_unassigned = false; betterShapeHoles[ s2Idx ].push( ho ); } else { ambiguous = true; } } } if ( hole_unassigned ) { betterShapeHoles[ sIdx ].push( ho ); } } } // console.log("ambiguous: ", ambiguous); if ( toChange.length > 0 ) { // console.log("to change: ", toChange); if ( ! ambiguous ) { newShapeHoles = betterShapeHoles; } } } var tmpHoles; for ( var i = 0, il = newShapes.length; i < il; i ++ ) { tmpShape = newShapes[ i ].s; shapes.push( tmpShape ); tmpHoles = newShapeHoles[ i ]; for ( var j = 0, jl = tmpHoles.length; j < jl; j ++ ) { tmpShape.holes.push( tmpHoles[ j ].h ); } } //console.log("shape", shapes); return shapes; } } ); /** * @author zz85 / http://www.lab4games.net/zz85/blog * @author mrdoob / http://mrdoob.com/ */ function Font( data ) { this.type = 'Font'; this.data = data; } Object.assign( Font.prototype, { isFont: true, generateShapes: function ( text, size ) { if ( size === undefined ) { size = 100; } var shapes = []; var paths = createPaths( text, size, this.data ); for ( var p = 0, pl = paths.length; p < pl; p ++ ) { Array.prototype.push.apply( shapes, paths[ p ].toShapes() ); } return shapes; } } ); function createPaths( text, size, data ) { var chars = Array.from ? Array.from( text ) : String( text ).split( '' ); // workaround for IE11, see #13988 var scale = size / data.resolution; var line_height = ( data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness ) * scale; var paths = []; var offsetX = 0, offsetY = 0; for ( var i = 0; i < chars.length; i ++ ) { var char = chars[ i ]; if ( char === '\n' ) { offsetX = 0; offsetY -= line_height; } else { var ret = createPath( char, scale, offsetX, offsetY, data ); offsetX += ret.offsetX; paths.push( ret.path ); } } return paths; } function createPath( char, scale, offsetX, offsetY, data ) { var glyph = data.glyphs[ char ] || data.glyphs[ '?' ]; if ( ! glyph ) { console.error( 'THREE.Font: character "' + char + '" does not exists in font family ' + data.familyName + '.' ); return; } var path = new ShapePath(); var x, y, cpx, cpy, cpx1, cpy1, cpx2, cpy2; if ( glyph.o ) { var outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) ); for ( var i = 0, l = outline.length; i < l; ) { var action = outline[ i ++ ]; switch ( action ) { case 'm': // moveTo x = outline[ i ++ ] * scale + offsetX; y = outline[ i ++ ] * scale + offsetY; path.moveTo( x, y ); break; case 'l': // lineTo x = outline[ i ++ ] * scale + offsetX; y = outline[ i ++ ] * scale + offsetY; path.lineTo( x, y ); break; case 'q': // quadraticCurveTo cpx = outline[ i ++ ] * scale + offsetX; cpy = outline[ i ++ ] * scale + offsetY; cpx1 = outline[ i ++ ] * scale + offsetX; cpy1 = outline[ i ++ ] * scale + offsetY; path.quadraticCurveTo( cpx1, cpy1, cpx, cpy ); break; case 'b': // bezierCurveTo cpx = outline[ i ++ ] * scale + offsetX; cpy = outline[ i ++ ] * scale + offsetY; cpx1 = outline[ i ++ ] * scale + offsetX; cpy1 = outline[ i ++ ] * scale + offsetY; cpx2 = outline[ i ++ ] * scale + offsetX; cpy2 = outline[ i ++ ] * scale + offsetY; path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy ); break; } } } return { offsetX: glyph.ha * scale, path: path }; } /** * @author mrdoob / http://mrdoob.com/ */ function FontLoader( manager ) { Loader.call( this, manager ); } FontLoader.prototype = Object.assign( Object.create( Loader.prototype ), { constructor: FontLoader, load: function ( url, onLoad, onProgress, onError ) { var scope = this; var loader = new FileLoader( this.manager ); loader.setPath( this.path ); loader.load( url, function ( text ) { var json; try { json = JSON.parse( text ); } catch ( e ) { console.warn( 'THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.' ); json = JSON.parse( text.substring( 65, text.length - 2 ) ); } var font = scope.parse( json ); if ( onLoad ) { onLoad( font ); } }, onProgress, onError ); }, parse: function ( json ) { return new Font( json ); } } ); /** * @author mrdoob / http://mrdoob.com/ */ var _context; var AudioContext = { getContext: function () { if ( _context === undefined ) { _context = new ( window.AudioContext || window.webkitAudioContext )(); } return _context; }, setContext: function ( value ) { _context = value; } }; /** * @author Reece Aaron Lecrivain / http://reecenotes.com/ */ function AudioLoader( manager ) { Loader.call( this, manager ); } AudioLoader.prototype = Object.assign( Object.create( Loader.prototype ), { constructor: AudioLoader, load: function ( url, onLoad, onProgress, onError ) { var loader = new FileLoader( this.manager ); loader.setResponseType( 'arraybuffer' ); loader.setPath( this.path ); loader.load( url, function ( buffer ) { // Create a copy of the buffer. The `decodeAudioData` method // detaches the buffer when complete, preventing reuse. var bufferCopy = buffer.slice( 0 ); var context = AudioContext.getContext(); context.decodeAudioData( bufferCopy, function ( audioBuffer ) { onLoad( audioBuffer ); } ); }, onProgress, onError ); } } ); /** * @author bhouston / http://clara.io * @author WestLangley / http://github.com/WestLangley * * Primary reference: * https://graphics.stanford.edu/papers/envmap/envmap.pdf * * Secondary reference: * https://www.ppsloan.org/publications/StupidSH36.pdf */ // 3-band SH defined by 9 coefficients function SphericalHarmonics3() { this.coefficients = []; for ( var i = 0; i < 9; i ++ ) { this.coefficients.push( new Vector3() ); } } Object.assign( SphericalHarmonics3.prototype, { isSphericalHarmonics3: true, set: function ( coefficients ) { for ( var i = 0; i < 9; i ++ ) { this.coefficients[ i ].copy( coefficients[ i ] ); } return this; }, zero: function () { for ( var i = 0; i < 9; i ++ ) { this.coefficients[ i ].set( 0, 0, 0 ); } return this; }, // get the radiance in the direction of the normal // target is a Vector3 getAt: function ( normal, target ) { // normal is assumed to be unit length var x = normal.x, y = normal.y, z = normal.z; var coeff = this.coefficients; // band 0 target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 ); // band 1 target.addScale( coeff[ 1 ], 0.488603 * y ); target.addScale( coeff[ 2 ], 0.488603 * z ); target.addScale( coeff[ 3 ], 0.488603 * x ); // band 2 target.addScale( coeff[ 4 ], 1.092548 * ( x * y ) ); target.addScale( coeff[ 5 ], 1.092548 * ( y * z ) ); target.addScale( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) ); target.addScale( coeff[ 7 ], 1.092548 * ( x * z ) ); target.addScale( coeff[ 8 ], 0.546274 * ( x * x - y * y ) ); return target; }, // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal // target is a Vector3 // https://graphics.stanford.edu/papers/envmap/envmap.pdf getIrradianceAt: function ( normal, target ) { // normal is assumed to be unit length var x = normal.x, y = normal.y, z = normal.z; var coeff = this.coefficients; // band 0 target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095 // band 1 target.addScale( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603 target.addScale( coeff[ 2 ], 2.0 * 0.511664 * z ); target.addScale( coeff[ 3 ], 2.0 * 0.511664 * x ); // band 2 target.addScale( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548 target.addScale( coeff[ 5 ], 2.0 * 0.429043 * y * z ); target.addScale( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3 target.addScale( coeff[ 7 ], 2.0 * 0.429043 * x * z ); target.addScale( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274 return target; }, add: function ( sh ) { for ( var i = 0; i < 9; i ++ ) { this.coefficients[ i ].add( sh.coefficients[ i ] ); } return this; }, scale: function ( s ) { for ( var i = 0; i < 9; i ++ ) { this.coefficients[ i ].multiplyScalar( s ); } return this; }, lerp: function ( sh, alpha ) { for ( var i = 0; i < 9; i ++ ) { this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha ); } return this; }, equals: function ( sh ) { for ( var i = 0; i < 9; i ++ ) { if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) { return false; } } return true; }, copy: function ( sh ) { return this.set( sh.coefficients ); }, clone: function () { return new this.constructor().copy( this ); }, fromArray: function ( array, offset ) { if ( offset === undefined ) { offset = 0; } var coefficients = this.coefficients; for ( var i = 0; i < 9; i ++ ) { coefficients[ i ].fromArray( array, offset + ( i * 3 ) ); } return this; }, toArray: function ( array, offset ) { if ( array === undefined ) { array = []; } if ( offset === undefined ) { offset = 0; } var coefficients = this.coefficients; for ( var i = 0; i < 9; i ++ ) { coefficients[ i ].toArray( array, offset + ( i * 3 ) ); } return array; } } ); Object.assign( SphericalHarmonics3, { // evaluate the basis functions // shBasis is an Array[ 9 ] getBasisAt: function ( normal, shBasis ) { // normal is assumed to be unit length var x = normal.x, y = normal.y, z = normal.z; // band 0 shBasis[ 0 ] = 0.282095; // band 1 shBasis[ 1 ] = 0.488603 * y; shBasis[ 2 ] = 0.488603 * z; shBasis[ 3 ] = 0.488603 * x; // band 2 shBasis[ 4 ] = 1.092548 * x * y; shBasis[ 5 ] = 1.092548 * y * z; shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 ); shBasis[ 7 ] = 1.092548 * x * z; shBasis[ 8 ] = 0.546274 * ( x * x - y * y ); } } ); /** * @author WestLangley / http://github.com/WestLangley * * A LightProbe is a source of indirect-diffuse light */ function LightProbe( sh, intensity ) { Light.call( this, undefined, intensity ); this.sh = ( sh !== undefined ) ? sh : new SphericalHarmonics3(); } LightProbe.prototype = Object.assign( Object.create( Light.prototype ), { constructor: LightProbe, isLightProbe: true, copy: function ( source ) { Light.prototype.copy.call( this, source ); this.sh.copy( source.sh ); this.intensity = source.intensity; return this; }, toJSON: function ( meta ) { var data = Light.prototype.toJSON.call( this, meta ); // data.sh = this.sh.toArray(); // todo return data; } } ); /** * @author WestLangley / http://github.com/WestLangley */ function HemisphereLightProbe( skyColor, groundColor, intensity ) { LightProbe.call( this, undefined, intensity ); var color1 = new Color().set( skyColor ); var color2 = new Color().set( groundColor ); var sky = new Vector3( color1.r, color1.g, color1.b ); var ground = new Vector3( color2.r, color2.g, color2.b ); // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI ); var c0 = Math.sqrt( Math.PI ); var c1 = c0 * Math.sqrt( 0.75 ); this.sh.coefficients[ 0 ].copy( sky ).add( ground ).multiplyScalar( c0 ); this.sh.coefficients[ 1 ].copy( sky ).sub( ground ).multiplyScalar( c1 ); } HemisphereLightProbe.prototype = Object.assign( Object.create( LightProbe.prototype ), { constructor: HemisphereLightProbe, isHemisphereLightProbe: true, copy: function ( source ) { // modifying colors not currently supported LightProbe.prototype.copy.call( this, source ); return this; }, toJSON: function ( meta ) { var data = LightProbe.prototype.toJSON.call( this, meta ); // data.sh = this.sh.toArray(); // todo return data; } } ); /** * @author WestLangley / http://github.com/WestLangley */ function AmbientLightProbe( color, intensity ) { LightProbe.call( this, undefined, intensity ); var color1 = new Color().set( color ); // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI ); this.sh.coefficients[ 0 ].set( color1.r, color1.g, color1.b ).multiplyScalar( 2 * Math.sqrt( Math.PI ) ); } AmbientLightProbe.prototype = Object.assign( Object.create( LightProbe.prototype ), { constructor: AmbientLightProbe, isAmbientLightProbe: true, copy: function ( source ) { // modifying color not currently supported LightProbe.prototype.copy.call( this, source ); return this; }, toJSON: function ( meta ) { var data = LightProbe.prototype.toJSON.call( this, meta ); // data.sh = this.sh.toArray(); // todo return data; } } ); var _eyeRight = new Matrix4(); var _eyeLeft = new Matrix4(); /** * @author mrdoob / http://mrdoob.com/ */ function StereoCamera() { this.type = 'StereoCamera'; this.aspect = 1; this.eyeSep = 0.064; this.cameraL = new PerspectiveCamera(); this.cameraL.layers.enable( 1 ); this.cameraL.matrixAutoUpdate = false; this.cameraR = new PerspectiveCamera(); this.cameraR.layers.enable( 2 ); this.cameraR.matrixAutoUpdate = false; this._cache = { focus: null, fov: null, aspect: null, near: null, far: null, zoom: null, eyeSep: null }; } Object.assign( StereoCamera.prototype, { update: function ( camera ) { var cache = this._cache; var needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov || cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near || cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep; if ( needsUpdate ) { cache.focus = camera.focus; cache.fov = camera.fov; cache.aspect = camera.aspect * this.aspect; cache.near = camera.near; cache.far = camera.far; cache.zoom = camera.zoom; cache.eyeSep = this.eyeSep; // Off-axis stereoscopic effect based on // http://paulbourke.net/stereographics/stereorender/ var projectionMatrix = camera.projectionMatrix.clone(); var eyeSepHalf = cache.eyeSep / 2; var eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus; var ymax = ( cache.near * Math.tan( MathUtils.DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom; var xmin, xmax; // translate xOffset _eyeLeft.elements[ 12 ] = - eyeSepHalf; _eyeRight.elements[ 12 ] = eyeSepHalf; // for left eye xmin = - ymax * cache.aspect + eyeSepOnProjection; xmax = ymax * cache.aspect + eyeSepOnProjection; projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin ); projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin ); this.cameraL.projectionMatrix.copy( projectionMatrix ); // for right eye xmin = - ymax * cache.aspect - eyeSepOnProjection; xmax = ymax * cache.aspect - eyeSepOnProjection; projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin ); projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin ); this.cameraR.projectionMatrix.copy( projectionMatrix ); } this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft ); this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight ); } } ); /** * @author alteredq / http://alteredqualia.com/ */ function Clock( autoStart ) { this.autoStart = ( autoStart !== undefined ) ? autoStart : true; this.startTime = 0; this.oldTime = 0; this.elapsedTime = 0; this.running = false; } Object.assign( Clock.prototype, { start: function () { this.startTime = ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732 this.oldTime = this.startTime; this.elapsedTime = 0; this.running = true; }, stop: function () { this.getElapsedTime(); this.running = false; this.autoStart = false; }, getElapsedTime: function () { this.getDelta(); return this.elapsedTime; }, getDelta: function () { var diff = 0; if ( this.autoStart && ! this.running ) { this.start(); return 0; } if ( this.running ) { var newTime = ( typeof performance === 'undefined' ? Date : performance ).now(); diff = ( newTime - this.oldTime ) / 1000; this.oldTime = newTime; this.elapsedTime += diff; } return diff; } } ); /** * @author mrdoob / http://mrdoob.com/ */ var _position$2 = new Vector3(); var _quaternion$3 = new Quaternion(); var _scale$1 = new Vector3(); var _orientation = new Vector3(); function AudioListener() { Object3D.call( this ); this.type = 'AudioListener'; this.context = AudioContext.getContext(); this.gain = this.context.createGain(); this.gain.connect( this.context.destination ); this.filter = null; this.timeDelta = 0; // private this._clock = new Clock(); } AudioListener.prototype = Object.assign( Object.create( Object3D.prototype ), { constructor: AudioListener, getInput: function () { return this.gain; }, removeFilter: function ( ) { if ( this.filter !== null ) { this.gain.disconnect( this.filter ); this.filter.disconnect( this.context.destination ); this.gain.connect( this.context.destination ); this.filter = null; } return this; }, getFilter: function () { return this.filter; }, setFilter: function ( value ) { if ( this.filter !== null ) { this.gain.disconnect( this.filter ); this.filter.disconnect( this.context.destination ); } else { this.gain.disconnect( this.context.destination ); } this.filter = value; this.gain.connect( this.filter ); this.filter.connect( this.context.destination ); return this; }, getMasterVolume: function () { return this.gain.gain.value; }, setMasterVolume: function ( value ) { this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 ); return this; }, updateMatrixWorld: function ( force ) { Object3D.prototype.updateMatrixWorld.call( this, force ); var listener = this.context.listener; var up = this.up; this.timeDelta = this._clock.getDelta(); this.matrixWorld.decompose( _position$2, _quaternion$3, _scale$1 ); _orientation.set( 0, 0, - 1 ).applyQuaternion( _quaternion$3 ); if ( listener.positionX ) { // code path for Chrome (see #14393) var endTime = this.context.currentTime + this.timeDelta; listener.positionX.linearRampToValueAtTime( _position$2.x, endTime ); listener.positionY.linearRampToValueAtTime( _position$2.y, endTime ); listener.positionZ.linearRampToValueAtTime( _position$2.z, endTime ); listener.forwardX.linearRampToValueAtTime( _orientation.x, endTime ); listener.forwardY.linearRampToValueAtTime( _orientation.y, endTime ); listener.forwardZ.linearRampToValueAtTime( _orientation.z, endTime ); listener.upX.linearRampToValueAtTime( up.x, endTime ); listener.upY.linearRampToValueAtTime( up.y, endTime ); listener.upZ.linearRampToValueAtTime( up.z, endTime ); } else { listener.setPosition( _position$2.x, _position$2.y, _position$2.z ); listener.setOrientation( _orientation.x, _orientation.y, _orientation.z, up.x, up.y, up.z ); } } } ); /** * @author mrdoob / http://mrdoob.com/ * @author Reece Aaron Lecrivain / http://reecenotes.com/ */ function Audio( listener ) { Object3D.call( this ); this.type = 'Audio'; this.listener = listener; this.context = listener.context; this.gain = this.context.createGain(); this.gain.connect( listener.getInput() ); this.autoplay = false; this.buffer = null; this.detune = 0; this.loop = false; this.loopStart = 0; this.loopEnd = 0; this.offset = 0; this.duration = undefined; this.playbackRate = 1; this.isPlaying = false; this.hasPlaybackControl = true; this.sourceType = 'empty'; this._startedAt = 0; this._pausedAt = 0; this.filters = []; } Audio.prototype = Object.assign( Object.create( Object3D.prototype ), { constructor: Audio, getOutput: function () { return this.gain; }, setNodeSource: function ( audioNode ) { this.hasPlaybackControl = false; this.sourceType = 'audioNode'; this.source = audioNode; this.connect(); return this; }, setMediaElementSource: function ( mediaElement ) { this.hasPlaybackControl = false; this.sourceType = 'mediaNode'; this.source = this.context.createMediaElementSource( mediaElement ); this.connect(); return this; }, setMediaStreamSource: function ( mediaStream ) { this.hasPlaybackControl = false; this.sourceType = 'mediaStreamNode'; this.source = this.context.createMediaStreamSource( mediaStream ); this.connect(); return this; }, setBuffer: function ( audioBuffer ) { this.buffer = audioBuffer; this.sourceType = 'buffer'; if ( this.autoplay ) { this.play(); } return this; }, play: function ( delay ) { if ( delay === undefined ) { delay = 0; } if ( this.isPlaying === true ) { console.warn( 'THREE.Audio: Audio is already playing.' ); return; } if ( this.hasPlaybackControl === false ) { console.warn( 'THREE.Audio: this Audio has no playback control.' ); return; } this._startedAt = this.context.currentTime + delay; var source = this.context.createBufferSource(); source.buffer = this.buffer; source.loop = this.loop; source.loopStart = this.loopStart; source.loopEnd = this.loopEnd; source.onended = this.onEnded.bind( this ); source.start( this._startedAt, this._pausedAt + this.offset, this.duration ); this.isPlaying = true; this.source = source; this.setDetune( this.detune ); this.setPlaybackRate( this.playbackRate ); return this.connect(); }, pause: function () { if ( this.hasPlaybackControl === false ) { console.warn( 'THREE.Audio: this Audio has no playback control.' ); return; } if ( this.isPlaying === true ) { this._pausedAt = ( this.context.currentTime - this._startedAt ) * this.playbackRate; this.source.stop(); this.source.onended = null; this.isPlaying = false; } return this; }, stop: function () { if ( this.hasPlaybackControl === false ) { console.warn( 'THREE.Audio: this Audio has no playback control.' ); return; } this._pausedAt = 0; this.source.stop(); this.source.onended = null; this.isPlaying = false; return this; }, connect: function () { if ( this.filters.length > 0 ) { this.source.connect( this.filters[ 0 ] ); for ( var i = 1, l = this.filters.length; i < l; i ++ ) { this.filters[ i - 1 ].connect( this.filters[ i ] ); } this.filters[ this.filters.length - 1 ].connect( this.getOutput() ); } else { this.source.connect( this.getOutput() ); } return this; }, disconnect: function () { if ( this.filters.length > 0 ) { this.source.disconnect( this.filters[ 0 ] ); for ( var i = 1, l = this.filters.length; i < l; i ++ ) { this.filters[ i - 1 ].disconnect( this.filters[ i ] ); } this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() ); } else { this.source.disconnect( this.getOutput() ); } return this; }, getFilters: function () { return this.filters; }, setFilters: function ( value ) { if ( ! value ) { value = []; } if ( this.isPlaying === true ) { this.disconnect(); this.filters = value; this.connect(); } else { this.filters = value; } return this; }, setDetune: function ( value ) { this.detune = value; if ( this.source.detune === undefined ) { return; } // only set detune when available if ( this.isPlaying === true ) { this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 ); } return this; }, getDetune: function () { return this.detune; }, getFilter: function () { return this.getFilters()[ 0 ]; }, setFilter: function ( filter ) { return this.setFilters( filter ? [ filter ] : [] ); }, setPlaybackRate: function ( value ) { if ( this.hasPlaybackControl === false ) { console.warn( 'THREE.Audio: this Audio has no playback control.' ); return; } this.playbackRate = value; if ( this.isPlaying === true ) { this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 ); } return this; }, getPlaybackRate: function () { return this.playbackRate; }, onEnded: function () { this.isPlaying = false; }, getLoop: function () { if ( this.hasPlaybackControl === false ) { console.warn( 'THREE.Audio: this Audio has no playback control.' ); return false; } return this.loop; }, setLoop: function ( value ) { if ( this.hasPlaybackControl === false ) { console.warn( 'THREE.Audio: this Audio has no playback control.' ); return; } this.loop = value; if ( this.isPlaying === true ) { this.source.loop = this.loop; } return this; }, setLoopStart: function ( value ) { this.loopStart = value; return this; }, setLoopEnd: function ( value ) { this.loopEnd = value; return this; }, getVolume: function () { return this.gain.gain.value; }, setVolume: function ( value ) { this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 ); return this; } } ); /** * @author mrdoob / http://mrdoob.com/ */ var _position$3 = new Vector3(); var _quaternion$4 = new Quaternion(); var _scale$2 = new Vector3(); var _orientation$1 = new Vector3(); function PositionalAudio( listener ) { Audio.call( this, listener ); this.panner = this.context.createPanner(); this.panner.panningModel = 'HRTF'; this.panner.connect( this.gain ); } PositionalAudio.prototype = Object.assign( Object.create( Audio.prototype ), { constructor: PositionalAudio, getOutput: function () { return this.panner; }, getRefDistance: function () { return this.panner.refDistance; }, setRefDistance: function ( value ) { this.panner.refDistance = value; return this; }, getRolloffFactor: function () { return this.panner.rolloffFactor; }, setRolloffFactor: function ( value ) { this.panner.rolloffFactor = value; return this; }, getDistanceModel: function () { return this.panner.distanceModel; }, setDistanceModel: function ( value ) { this.panner.distanceModel = value; return this; }, getMaxDistance: function () { return this.panner.maxDistance; }, setMaxDistance: function ( value ) { this.panner.maxDistance = value; return this; }, setDirectionalCone: function ( coneInnerAngle, coneOuterAngle, coneOuterGain ) { this.panner.coneInnerAngle = coneInnerAngle; this.panner.coneOuterAngle = coneOuterAngle; this.panner.coneOuterGain = coneOuterGain; return this; }, updateMatrixWorld: function ( force ) { Object3D.prototype.updateMatrixWorld.call( this, force ); if ( this.hasPlaybackControl === true && this.isPlaying === false ) { return; } this.matrixWorld.decompose( _position$3, _quaternion$4, _scale$2 ); _orientation$1.set( 0, 0, 1 ).applyQuaternion( _quaternion$4 ); var panner = this.panner; if ( panner.positionX ) { // code path for Chrome and Firefox (see #14393) var endTime = this.context.currentTime + this.listener.timeDelta; panner.positionX.linearRampToValueAtTime( _position$3.x, endTime ); panner.positionY.linearRampToValueAtTime( _position$3.y, endTime ); panner.positionZ.linearRampToValueAtTime( _position$3.z, endTime ); panner.orientationX.linearRampToValueAtTime( _orientation$1.x, endTime ); panner.orientationY.linearRampToValueAtTime( _orientation$1.y, endTime ); panner.orientationZ.linearRampToValueAtTime( _orientation$1.z, endTime ); } else { panner.setPosition( _position$3.x, _position$3.y, _position$3.z ); panner.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z ); } } } ); /** * @author mrdoob / http://mrdoob.com/ */ function AudioAnalyser( audio, fftSize ) { this.analyser = audio.context.createAnalyser(); this.analyser.fftSize = fftSize !== undefined ? fftSize : 2048; this.data = new Uint8Array( this.analyser.frequencyBinCount ); audio.getOutput().connect( this.analyser ); } Object.assign( AudioAnalyser.prototype, { getFrequencyData: function () { this.analyser.getByteFrequencyData( this.data ); return this.data; }, getAverageFrequency: function () { var value = 0, data = this.getFrequencyData(); for ( var i = 0; i < data.length; i ++ ) { value += data[ i ]; } return value / data.length; } } ); /** * * Buffered scene graph property that allows weighted accumulation. * * * @author Ben Houston / http://clara.io/ * @author David Sarno / http://lighthaus.us/ * @author tschw */ function PropertyMixer( binding, typeName, valueSize ) { this.binding = binding; this.valueSize = valueSize; var bufferType = Float64Array, mixFunction; switch ( typeName ) { case 'quaternion': mixFunction = this._slerp; break; case 'string': case 'bool': bufferType = Array; mixFunction = this._select; break; default: mixFunction = this._lerp; } this.buffer = new bufferType( valueSize * 4 ); // layout: [ incoming | accu0 | accu1 | orig ] // // interpolators can use .buffer as their .result // the data then goes to 'incoming' // // 'accu0' and 'accu1' are used frame-interleaved for // the cumulative result and are compared to detect // changes // // 'orig' stores the original state of the property this._mixBufferRegion = mixFunction; this.cumulativeWeight = 0; this.useCount = 0; this.referenceCount = 0; } Object.assign( PropertyMixer.prototype, { // accumulate data in the 'incoming' region into 'accu' accumulate: function ( accuIndex, weight ) { // note: happily accumulating nothing when weight = 0, the caller knows // the weight and shouldn't have made the call in the first place var buffer = this.buffer, stride = this.valueSize, offset = accuIndex * stride + stride, currentWeight = this.cumulativeWeight; if ( currentWeight === 0 ) { // accuN := incoming * weight for ( var i = 0; i !== stride; ++ i ) { buffer[ offset + i ] = buffer[ i ]; } currentWeight = weight; } else { // accuN := accuN + incoming * weight currentWeight += weight; var mix = weight / currentWeight; this._mixBufferRegion( buffer, offset, 0, mix, stride ); } this.cumulativeWeight = currentWeight; }, // apply the state of 'accu' to the binding when accus differ apply: function ( accuIndex ) { var stride = this.valueSize, buffer = this.buffer, offset = accuIndex * stride + stride, weight = this.cumulativeWeight, binding = this.binding; this.cumulativeWeight = 0; if ( weight < 1 ) { // accuN := accuN + original * ( 1 - cumulativeWeight ) var originalValueOffset = stride * 3; this._mixBufferRegion( buffer, offset, originalValueOffset, 1 - weight, stride ); } for ( var i = stride, e = stride + stride; i !== e; ++ i ) { if ( buffer[ i ] !== buffer[ i + stride ] ) { // value has changed -> update scene graph binding.setValue( buffer, offset ); break; } } }, // remember the state of the bound property and copy it to both accus saveOriginalState: function () { var binding = this.binding; var buffer = this.buffer, stride = this.valueSize, originalValueOffset = stride * 3; binding.getValue( buffer, originalValueOffset ); // accu[0..1] := orig -- initially detect changes against the original for ( var i = stride, e = originalValueOffset; i !== e; ++ i ) { buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ]; } this.cumulativeWeight = 0; }, // apply the state previously taken via 'saveOriginalState' to the binding restoreOriginalState: function () { var originalValueOffset = this.valueSize * 3; this.binding.setValue( this.buffer, originalValueOffset ); }, // mix functions _select: function ( buffer, dstOffset, srcOffset, t, stride ) { if ( t >= 0.5 ) { for ( var i = 0; i !== stride; ++ i ) { buffer[ dstOffset + i ] = buffer[ srcOffset + i ]; } } }, _slerp: function ( buffer, dstOffset, srcOffset, t ) { Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t ); }, _lerp: function ( buffer, dstOffset, srcOffset, t, stride ) { var s = 1 - t; for ( var i = 0; i !== stride; ++ i ) { var j = dstOffset + i; buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t; } } } ); /** * * A reference to a real property in the scene graph. * * * @author Ben Houston / http://clara.io/ * @author David Sarno / http://lighthaus.us/ * @author tschw */ // Characters [].:/ are reserved for track binding syntax. var _RESERVED_CHARS_RE = '\\[\\]\\.:\\/'; var _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' ); // Attempts to allow node names from any language. ES5's `\w` regexp matches // only latin characters, and the unicode \p{L} is not yet supported. So // instead, we exclude reserved characters and match everything else. var _wordChar = '[^' + _RESERVED_CHARS_RE + ']'; var _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']'; // Parent directories, delimited by '/' or ':'. Currently unused, but must // be matched to parse the rest of the track name. var _directoryRe = /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar ); // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'. var _nodeRe = /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot ); // Object on target node, and accessor. May not contain reserved // characters. Accessor may contain any character except closing bracket. var _objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar ); // Property and accessor. May not contain reserved characters. Accessor may // contain any non-bracket characters. var _propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar ); var _trackRe = new RegExp( '' + '^' + _directoryRe + _nodeRe + _objectRe + _propertyRe + '$' ); var _supportedObjectNames = [ 'material', 'materials', 'bones' ]; function Composite( targetGroup, path, optionalParsedPath ) { var parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path ); this._targetGroup = targetGroup; this._bindings = targetGroup.subscribe_( path, parsedPath ); } Object.assign( Composite.prototype, { getValue: function ( array, offset ) { this.bind(); // bind all binding var firstValidIndex = this._targetGroup.nCachedObjects_, binding = this._bindings[ firstValidIndex ]; // and only call .getValue on the first if ( binding !== undefined ) { binding.getValue( array, offset ); } }, setValue: function ( array, offset ) { var bindings = this._bindings; for ( var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) { bindings[ i ].setValue( array, offset ); } }, bind: function () { var bindings = this._bindings; for ( var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) { bindings[ i ].bind(); } }, unbind: function () { var bindings = this._bindings; for ( var i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) { bindings[ i ].unbind(); } } } ); function PropertyBinding( rootNode, path, parsedPath ) { this.path = path; this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path ); this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName ) || rootNode; this.rootNode = rootNode; } Object.assign( PropertyBinding, { Composite: Composite, create: function ( root, path, parsedPath ) { if ( ! ( root && root.isAnimationObjectGroup ) ) { return new PropertyBinding( root, path, parsedPath ); } else { return new PropertyBinding.Composite( root, path, parsedPath ); } }, /** * Replaces spaces with underscores and removes unsupported characters from * node names, to ensure compatibility with parseTrackName(). * * @param {string} name Node name to be sanitized. * @return {string} */ sanitizeNodeName: function ( name ) { return name.replace( /\s/g, '_' ).replace( _reservedRe, '' ); }, parseTrackName: function ( trackName ) { var matches = _trackRe.exec( trackName ); if ( ! matches ) { throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName ); } var results = { // directoryName: matches[ 1 ], // (tschw) currently unused nodeName: matches[ 2 ], objectName: matches[ 3 ], objectIndex: matches[ 4 ], propertyName: matches[ 5 ], // required propertyIndex: matches[ 6 ] }; var lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' ); if ( lastDot !== undefined && lastDot !== - 1 ) { var objectName = results.nodeName.substring( lastDot + 1 ); // Object names must be checked against a whitelist. Otherwise, there // is no way to parse 'foo.bar.baz': 'baz' must be a property, but // 'bar' could be the objectName, or part of a nodeName (which can // include '.' characters). if ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) { results.nodeName = results.nodeName.substring( 0, lastDot ); results.objectName = objectName; } } if ( results.propertyName === null || results.propertyName.length === 0 ) { throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName ); } return results; }, findNode: function ( root, nodeName ) { if ( ! nodeName || nodeName === "" || nodeName === "root" || nodeName === "." || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) { return root; } // search into skeleton bones. if ( root.skeleton ) { var bone = root.skeleton.getBoneByName( nodeName ); if ( bone !== undefined ) { return bone; } } // search into node subtree. if ( root.children ) { var searchNodeSubtree = function ( children ) { for ( var i = 0; i < children.length; i ++ ) { var childNode = children[ i ]; if ( childNode.name === nodeName || childNode.uuid === nodeName ) { return childNode; } var result = searchNodeSubtree( childNode.children ); if ( result ) { return result; } } return null; }; var subTreeNode = searchNodeSubtree( root.children ); if ( subTreeNode ) { return subTreeNode; } } return null; } } ); Object.assign( PropertyBinding.prototype, { // prototype, continued // these are used to "bind" a nonexistent property _getValue_unavailable: function () {}, _setValue_unavailable: function () {}, BindingType: { Direct: 0, EntireArray: 1, ArrayElement: 2, HasFromToArray: 3 }, Versioning: { None: 0, NeedsUpdate: 1, MatrixWorldNeedsUpdate: 2 }, GetterByBindingType: [ function getValue_direct( buffer, offset ) { buffer[ offset ] = this.node[ this.propertyName ]; }, function getValue_array( buffer, offset ) { var source = this.resolvedProperty; for ( var i = 0, n = source.length; i !== n; ++ i ) { buffer[ offset ++ ] = source[ i ]; } }, function getValue_arrayElement( buffer, offset ) { buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ]; }, function getValue_toArray( buffer, offset ) { this.resolvedProperty.toArray( buffer, offset ); } ], SetterByBindingTypeAndVersioning: [ [ // Direct function setValue_direct( buffer, offset ) { this.targetObject[ this.propertyName ] = buffer[ offset ]; }, function setValue_direct_setNeedsUpdate( buffer, offset ) { this.targetObject[ this.propertyName ] = buffer[ offset ]; this.targetObject.needsUpdate = true; }, function setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) { this.targetObject[ this.propertyName ] = buffer[ offset ]; this.targetObject.matrixWorldNeedsUpdate = true; } ], [ // EntireArray function setValue_array( buffer, offset ) { var dest = this.resolvedProperty; for ( var i = 0, n = dest.length; i !== n; ++ i ) { dest[ i ] = buffer[ offset ++ ]; } }, function setValue_array_setNeedsUpdate( buffer, offset ) { var dest = this.resolvedProperty; for ( var i = 0, n = dest.length; i !== n; ++ i ) { dest[ i ] = buffer[ offset ++ ]; } this.targetObject.needsUpdate = true; }, function setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) { var dest = this.resolvedProperty; for ( var i = 0, n = dest.length; i !== n; ++ i ) { dest[ i ] = buffer[ offset ++ ]; } this.targetObject.matrixWorldNeedsUpdate = true; } ], [ // ArrayElement function setValue_arrayElement( buffer, offset ) { this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ]; }, function setValue_arrayElement_setNeedsUpdate( buffer, offset ) { this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ]; this.targetObject.needsUpdate = true; }, function setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) { this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ]; this.targetObject.matrixWorldNeedsUpdate = true; } ], [ // HasToFromArray function setValue_fromArray( buffer, offset ) { this.resolvedProperty.fromArray( buffer, offset ); }, function setValue_fromArray_setNeedsUpdate( buffer, offset ) { this.resolvedProperty.fromArray( buffer, offset ); this.targetObject.needsUpdate = true; }, function setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) { this.resolvedProperty.fromArray( buffer, offset ); this.targetObject.matrixWorldNeedsUpdate = true; } ] ], getValue: function getValue_unbound( targetArray, offset ) { this.bind(); this.getValue( targetArray, offset ); // Note: This class uses a State pattern on a per-method basis: // 'bind' sets 'this.getValue' / 'setValue' and shadows the // prototype version of these methods with one that represents // the bound state. When the property is not found, the methods // become no-ops. }, setValue: function getValue_unbound( sourceArray, offset ) { this.bind(); this.setValue( sourceArray, offset ); }, // create getter / setter pair for a property in the scene graph bind: function () { var targetObject = this.node, parsedPath = this.parsedPath, objectName = parsedPath.objectName, propertyName = parsedPath.propertyName, propertyIndex = parsedPath.propertyIndex; if ( ! targetObject ) { targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName ) || this.rootNode; this.node = targetObject; } // set fail state so we can just 'return' on error this.getValue = this._getValue_unavailable; this.setValue = this._setValue_unavailable; // ensure there is a value node if ( ! targetObject ) { console.error( 'THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.' ); return; } if ( objectName ) { var objectIndex = parsedPath.objectIndex; // special cases were we need to reach deeper into the hierarchy to get the face materials.... switch ( objectName ) { case 'materials': if ( ! targetObject.material ) { console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this ); return; } if ( ! targetObject.material.materials ) { console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this ); return; } targetObject = targetObject.material.materials; break; case 'bones': if ( ! targetObject.skeleton ) { console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this ); return; } // potential future optimization: skip this if propertyIndex is already an integer // and convert the integer string to a true integer. targetObject = targetObject.skeleton.bones; // support resolving morphTarget names into indices. for ( var i = 0; i < targetObject.length; i ++ ) { if ( targetObject[ i ].name === objectIndex ) { objectIndex = i; break; } } break; default: if ( targetObject[ objectName ] === undefined ) { console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this ); return; } targetObject = targetObject[ objectName ]; } if ( objectIndex !== undefined ) { if ( targetObject[ objectIndex ] === undefined ) { console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject ); return; } targetObject = targetObject[ objectIndex ]; } } // resolve property var nodeProperty = targetObject[ propertyName ]; if ( nodeProperty === undefined ) { var nodeName = parsedPath.nodeName; console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName + '.' + propertyName + ' but it wasn\'t found.', targetObject ); return; } // determine versioning scheme var versioning = this.Versioning.None; this.targetObject = targetObject; if ( targetObject.needsUpdate !== undefined ) { // material versioning = this.Versioning.NeedsUpdate; } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform versioning = this.Versioning.MatrixWorldNeedsUpdate; } // determine how the property gets bound var bindingType = this.BindingType.Direct; if ( propertyIndex !== undefined ) { // access a sub element of the property array (only primitives are supported right now) if ( propertyName === "morphTargetInfluences" ) { // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer. // support resolving morphTarget names into indices. if ( ! targetObject.geometry ) { console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this ); return; } if ( targetObject.geometry.isBufferGeometry ) { if ( ! targetObject.geometry.morphAttributes ) { console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this ); return; } for ( var i = 0; i < this.node.geometry.morphAttributes.position.length; i ++ ) { if ( targetObject.geometry.morphAttributes.position[ i ].name === propertyIndex ) { propertyIndex = i; break; } } } else { if ( ! targetObject.geometry.morphTargets ) { console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphTargets.', this ); return; } for ( var i = 0; i < this.node.geometry.morphTargets.length; i ++ ) { if ( targetObject.geometry.morphTargets[ i ].name === propertyIndex ) { propertyIndex = i; break; } } } } bindingType = this.BindingType.ArrayElement; this.resolvedProperty = nodeProperty; this.propertyIndex = propertyIndex; } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) { // must use copy for Object3D.Euler/Quaternion bindingType = this.BindingType.HasFromToArray; this.resolvedProperty = nodeProperty; } else if ( Array.isArray( nodeProperty ) ) { bindingType = this.BindingType.EntireArray; this.resolvedProperty = nodeProperty; } else { this.propertyName = propertyName; } // select getter / setter this.getValue = this.GetterByBindingType[ bindingType ]; this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ]; }, unbind: function () { this.node = null; // back to the prototype version of getValue / setValue // note: avoiding to mutate the shape of 'this' via 'delete' this.getValue = this._getValue_unbound; this.setValue = this._setValue_unbound; } } ); //!\ DECLARE ALIAS AFTER assign prototype ! Object.assign( PropertyBinding.prototype, { // initial state of these methods that calls 'bind' _getValue_unbound: PropertyBinding.prototype.getValue, _setValue_unbound: PropertyBinding.prototype.setValue, } ); /** * * A group of objects that receives a shared animation state. * * Usage: * * - Add objects you would otherwise pass as 'root' to the * constructor or the .clipAction method of AnimationMixer. * * - Instead pass this object as 'root'. * * - You can also add and remove objects later when the mixer * is running. * * Note: * * Objects of this class appear as one object to the mixer, * so cache control of the individual objects must be done * on the group. * * Limitation: * * - The animated properties must be compatible among the * all objects in the group. * * - A single property can either be controlled through a * target group or directly, but not both. * * @author tschw */ function AnimationObjectGroup() { this.uuid = MathUtils.generateUUID(); // cached objects followed by the active ones this._objects = Array.prototype.slice.call( arguments ); this.nCachedObjects_ = 0; // threshold // note: read by PropertyBinding.Composite var indices = {}; this._indicesByUUID = indices; // for bookkeeping for ( var i = 0, n = arguments.length; i !== n; ++ i ) { indices[ arguments[ i ].uuid ] = i; } this._paths = []; // inside: string this._parsedPaths = []; // inside: { we don't care, here } this._bindings = []; // inside: Array< PropertyBinding > this._bindingsIndicesByPath = {}; // inside: indices in these arrays var scope = this; this.stats = { objects: { get total() { return scope._objects.length; }, get inUse() { return this.total - scope.nCachedObjects_; } }, get bindingsPerObject() { return scope._bindings.length; } }; } Object.assign( AnimationObjectGroup.prototype, { isAnimationObjectGroup: true, add: function () { var objects = this._objects, nObjects = objects.length, nCachedObjects = this.nCachedObjects_, indicesByUUID = this._indicesByUUID, paths = this._paths, parsedPaths = this._parsedPaths, bindings = this._bindings, nBindings = bindings.length, knownObject = undefined; for ( var i = 0, n = arguments.length; i !== n; ++ i ) { var object = arguments[ i ], uuid = object.uuid, index = indicesByUUID[ uuid ]; if ( index === undefined ) { // unknown object -> add it to the ACTIVE region index = nObjects ++; indicesByUUID[ uuid ] = index; objects.push( object ); // accounting is done, now do the same for all bindings for ( var j = 0, m = nBindings; j !== m; ++ j ) { bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) ); } } else if ( index < nCachedObjects ) { knownObject = objects[ index ]; // move existing object to the ACTIVE region var firstActiveIndex = -- nCachedObjects, lastCachedObject = objects[ firstActiveIndex ]; indicesByUUID[ lastCachedObject.uuid ] = index; objects[ index ] = lastCachedObject; indicesByUUID[ uuid ] = firstActiveIndex; objects[ firstActiveIndex ] = object; // accounting is done, now do the same for all bindings for ( var j = 0, m = nBindings; j !== m; ++ j ) { var bindingsForPath = bindings[ j ], lastCached = bindingsForPath[ firstActiveIndex ], binding = bindingsForPath[ index ]; bindingsForPath[ index ] = lastCached; if ( binding === undefined ) { // since we do not bother to create new bindings // for objects that are cached, the binding may // or may not exist binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ); } bindingsForPath[ firstActiveIndex ] = binding; } } else if ( objects[ index ] !== knownObject ) { console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' + 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' ); } // else the object is already where we want it to be } // for arguments this.nCachedObjects_ = nCachedObjects; }, remove: function () { var objects = this._objects, nCachedObjects = this.nCachedObjects_, indicesByUUID = this._indicesByUUID, bindings = this._bindings, nBindings = bindings.length; for ( var i = 0, n = arguments.length; i !== n; ++ i ) { var object = arguments[ i ], uuid = object.uuid, index = indicesByUUID[ uuid ]; if ( index !== undefined && index >= nCachedObjects ) { // move existing object into the CACHED region var lastCachedIndex = nCachedObjects ++, firstActiveObject = objects[ lastCachedIndex ]; indicesByUUID[ firstActiveObject.uuid ] = index; objects[ index ] = firstActiveObject; indicesByUUID[ uuid ] = lastCachedIndex; objects[ lastCachedIndex ] = object; // accounting is done, now do the same for all bindings for ( var j = 0, m = nBindings; j !== m; ++ j ) { var bindingsForPath = bindings[ j ], firstActive = bindingsForPath[ lastCachedIndex ], binding = bindingsForPath[ index ]; bindingsForPath[ index ] = firstActive; bindingsForPath[ lastCachedIndex ] = binding; } } } // for arguments this.nCachedObjects_ = nCachedObjects; }, // remove & forget uncache: function () { var objects = this._objects, nObjects = objects.length, nCachedObjects = this.nCachedObjects_, indicesByUUID = this._indicesByUUID, bindings = this._bindings, nBindings = bindings.length; for ( var i = 0, n = arguments.length; i !== n; ++ i ) { var object = arguments[ i ], uuid = object.uuid, index = indicesByUUID[ uuid ]; if ( index !== undefined ) { delete indicesByUUID[ uuid ]; if ( index < nCachedObjects ) { // object is cached, shrink the CACHED region var firstActiveIndex = -- nCachedObjects, lastCachedObject = objects[ firstActiveIndex ], lastIndex = -- nObjects, lastObject = objects[ lastIndex ]; // last cached object takes this object's place indicesByUUID[ lastCachedObject.uuid ] = index; objects[ index ] = lastCachedObject; // last object goes to the activated slot and pop indicesByUUID[ lastObject.uuid ] = firstActiveIndex; objects[ firstActiveIndex ] = lastObject; objects.pop(); // accounting is done, now do the same for all bindings for ( var j = 0, m = nBindings; j !== m; ++ j ) { var bindingsForPath = bindings[ j ], lastCached = bindingsForPath[ firstActiveIndex ], last = bindingsForPath[ lastIndex ]; bindingsForPath[ index ] = lastCached; bindingsForPath[ firstActiveIndex ] = last; bindingsForPath.pop(); } } else { // object is active, just swap with the last and pop var lastIndex = -- nObjects, lastObject = objects[ lastIndex ]; indicesByUUID[ lastObject.uuid ] = index; objects[ index ] = lastObject; objects.pop(); // accounting is done, now do the same for all bindings for ( var j = 0, m = nBindings; j !== m; ++ j ) { var bindingsForPath = bindings[ j ]; bindingsForPath[ index ] = bindingsForPath[ lastIndex ]; bindingsForPath.pop(); } } // cached or active } // if object is known } // for arguments this.nCachedObjects_ = nCachedObjects; }, // Internal interface used by befriended PropertyBinding.Composite: subscribe_: function ( path, parsedPath ) { // returns an array of bindings for the given path that is changed // according to the contained objects in the group var indicesByPath = this._bindingsIndicesByPath, index = indicesByPath[ path ], bindings = this._bindings; if ( index !== undefined ) { return bindings[ index ]; } var paths = this._paths, parsedPaths = this._parsedPaths, objects = this._objects, nObjects = objects.length, nCachedObjects = this.nCachedObjects_, bindingsForPath = new Array( nObjects ); index = bindings.length; indicesByPath[ path ] = index; paths.push( path ); parsedPaths.push( parsedPath ); bindings.push( bindingsForPath ); for ( var i = nCachedObjects, n = objects.length; i !== n; ++ i ) { var object = objects[ i ]; bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath ); } return bindingsForPath; }, unsubscribe_: function ( path ) { // tells the group to forget about a property path and no longer // update the array previously obtained with 'subscribe_' var indicesByPath = this._bindingsIndicesByPath, index = indicesByPath[ path ]; if ( index !== undefined ) { var paths = this._paths, parsedPaths = this._parsedPaths, bindings = this._bindings, lastBindingsIndex = bindings.length - 1, lastBindings = bindings[ lastBindingsIndex ], lastBindingsPath = path[ lastBindingsIndex ]; indicesByPath[ lastBindingsPath ] = index; bindings[ index ] = lastBindings; bindings.pop(); parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ]; parsedPaths.pop(); paths[ index ] = paths[ lastBindingsIndex ]; paths.pop(); } } } ); /** * * Action provided by AnimationMixer for scheduling clip playback on specific * objects. * * @author Ben Houston / http://clara.io/ * @author David Sarno / http://lighthaus.us/ * @author tschw * */ function AnimationAction( mixer, clip, localRoot ) { this._mixer = mixer; this._clip = clip; this._localRoot = localRoot || null; var tracks = clip.tracks, nTracks = tracks.length, interpolants = new Array( nTracks ); var interpolantSettings = { endingStart: ZeroCurvatureEnding, endingEnd: ZeroCurvatureEnding }; for ( var i = 0; i !== nTracks; ++ i ) { var interpolant = tracks[ i ].createInterpolant( null ); interpolants[ i ] = interpolant; interpolant.settings = interpolantSettings; } this._interpolantSettings = interpolantSettings; this._interpolants = interpolants; // bound by the mixer // inside: PropertyMixer (managed by the mixer) this._propertyBindings = new Array( nTracks ); this._cacheIndex = null; // for the memory manager this._byClipCacheIndex = null; // for the memory manager this._timeScaleInterpolant = null; this._weightInterpolant = null; this.loop = LoopRepeat; this._loopCount = - 1; // global mixer time when the action is to be started // it's set back to 'null' upon start of the action this._startTime = null; // scaled local time of the action // gets clamped or wrapped to 0..clip.duration according to loop this.time = 0; this.timeScale = 1; this._effectiveTimeScale = 1; this.weight = 1; this._effectiveWeight = 1; this.repetitions = Infinity; // no. of repetitions when looping this.paused = false; // true -> zero effective time scale this.enabled = true; // false -> zero effective weight this.clampWhenFinished = false;// keep feeding the last frame? this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate this.zeroSlopeAtEnd = true;// clips for start, loop and end } Object.assign( AnimationAction.prototype, { // State & Scheduling play: function () { this._mixer._activateAction( this ); return this; }, stop: function () { this._mixer._deactivateAction( this ); return this.reset(); }, reset: function () { this.paused = false; this.enabled = true; this.time = 0; // restart clip this._loopCount = - 1;// forget previous loops this._startTime = null;// forget scheduling return this.stopFading().stopWarping(); }, isRunning: function () { return this.enabled && ! this.paused && this.timeScale !== 0 && this._startTime === null && this._mixer._isActiveAction( this ); }, // return true when play has been called isScheduled: function () { return this._mixer._isActiveAction( this ); }, startAt: function ( time ) { this._startTime = time; return this; }, setLoop: function ( mode, repetitions ) { this.loop = mode; this.repetitions = repetitions; return this; }, // Weight // set the weight stopping any scheduled fading // although .enabled = false yields an effective weight of zero, this // method does *not* change .enabled, because it would be confusing setEffectiveWeight: function ( weight ) { this.weight = weight; // note: same logic as when updated at runtime this._effectiveWeight = this.enabled ? weight : 0; return this.stopFading(); }, // return the weight considering fading and .enabled getEffectiveWeight: function () { return this._effectiveWeight; }, fadeIn: function ( duration ) { return this._scheduleFading( duration, 0, 1 ); }, fadeOut: function ( duration ) { return this._scheduleFading( duration, 1, 0 ); }, crossFadeFrom: function ( fadeOutAction, duration, warp ) { fadeOutAction.fadeOut( duration ); this.fadeIn( duration ); if ( warp ) { var fadeInDuration = this._clip.duration, fadeOutDuration = fadeOutAction._clip.duration, startEndRatio = fadeOutDuration / fadeInDuration, endStartRatio = fadeInDuration / fadeOutDuration; fadeOutAction.warp( 1.0, startEndRatio, duration ); this.warp( endStartRatio, 1.0, duration ); } return this; }, crossFadeTo: function ( fadeInAction, duration, warp ) { return fadeInAction.crossFadeFrom( this, duration, warp ); }, stopFading: function () { var weightInterpolant = this._weightInterpolant; if ( weightInterpolant !== null ) { this._weightInterpolant = null; this._mixer._takeBackControlInterpolant( weightInterpolant ); } return this; }, // Time Scale Control // set the time scale stopping any scheduled warping // although .paused = true yields an effective time scale of zero, this // method does *not* change .paused, because it would be confusing setEffectiveTimeScale: function ( timeScale ) { this.timeScale = timeScale; this._effectiveTimeScale = this.paused ? 0 : timeScale; return this.stopWarping(); }, // return the time scale considering warping and .paused getEffectiveTimeScale: function () { return this._effectiveTimeScale; }, setDuration: function ( duration ) { this.timeScale = this._clip.duration / duration; return this.stopWarping(); }, syncWith: function ( action ) { this.time = action.time; this.timeScale = action.timeScale; return this.stopWarping(); }, halt: function ( duration ) { return this.warp( this._effectiveTimeScale, 0, duration ); }, warp: function ( startTimeScale, endTimeScale, duration ) { var mixer = this._mixer, now = mixer.time, interpolant = this._timeScaleInterpolant, timeScale = this.timeScale; if ( interpolant === null ) { interpolant = mixer._lendControlInterpolant(); this._timeScaleInterpolant = interpolant; } var times = interpolant.parameterPositions, values = interpolant.sampleValues; times[ 0 ] = now; times[ 1 ] = now + duration; values[ 0 ] = startTimeScale / timeScale; values[ 1 ] = endTimeScale / timeScale; return this; }, stopWarping: function () { var timeScaleInterpolant = this._timeScaleInterpolant; if ( timeScaleInterpolant !== null ) { this._timeScaleInterpolant = null; this._mixer._takeBackControlInterpolant( timeScaleInterpolant ); } return this; }, // Object Accessors getMixer: function () { return this._mixer; }, getClip: function () { return this._clip; }, getRoot: function () { return this._localRoot || this._mixer._root; }, // Interna _update: function ( time, deltaTime, timeDirection, accuIndex ) { // called by the mixer if ( ! this.enabled ) { // call ._updateWeight() to update ._effectiveWeight this._updateWeight( time ); return; } var startTime = this._startTime; if ( startTime !== null ) { // check for scheduled start of action var timeRunning = ( time - startTime ) * timeDirection; if ( timeRunning < 0 || timeDirection === 0 ) { return; // yet to come / don't decide when delta = 0 } // start this._startTime = null; // unschedule deltaTime = timeDirection * timeRunning; } // apply time scale and advance time deltaTime *= this._updateTimeScale( time ); var clipTime = this._updateTime( deltaTime ); // note: _updateTime may disable the action resulting in // an effective weight of 0 var weight = this._updateWeight( time ); if ( weight > 0 ) { var interpolants = this._interpolants; var propertyMixers = this._propertyBindings; for ( var j = 0, m = interpolants.length; j !== m; ++ j ) { interpolants[ j ].evaluate( clipTime ); propertyMixers[ j ].accumulate( accuIndex, weight ); } } }, _updateWeight: function ( time ) { var weight = 0; if ( this.enabled ) { weight = this.weight; var interpolant = this._weightInterpolant; if ( interpolant !== null ) { var interpolantValue = interpolant.evaluate( time )[ 0 ]; weight *= interpolantValue; if ( time > interpolant.parameterPositions[ 1 ] ) { this.stopFading(); if ( interpolantValue === 0 ) { // faded out, disable this.enabled = false; } } } } this._effectiveWeight = weight; return weight; }, _updateTimeScale: function ( time ) { var timeScale = 0; if ( ! this.paused ) { timeScale = this.timeScale; var interpolant = this._timeScaleInterpolant; if ( interpolant !== null ) { var interpolantValue = interpolant.evaluate( time )[ 0 ]; timeScale *= interpolantValue; if ( time > interpolant.parameterPositions[ 1 ] ) { this.stopWarping(); if ( timeScale === 0 ) { // motion has halted, pause this.paused = true; } else { // warp done - apply final time scale this.timeScale = timeScale; } } } } this._effectiveTimeScale = timeScale; return timeScale; }, _updateTime: function ( deltaTime ) { var time = this.time + deltaTime; var duration = this._clip.duration; var loop = this.loop; var loopCount = this._loopCount; var pingPong = ( loop === LoopPingPong ); if ( deltaTime === 0 ) { if ( loopCount === - 1 ) { return time; } return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time; } if ( loop === LoopOnce ) { if ( loopCount === - 1 ) { // just started this._loopCount = 0; this._setEndings( true, true, false ); } handle_stop: { if ( time >= duration ) { time = duration; } else if ( time < 0 ) { time = 0; } else { this.time = time; break handle_stop; } if ( this.clampWhenFinished ) { this.paused = true; } else { this.enabled = false; } this.time = time; this._mixer.dispatchEvent( { type: 'finished', action: this, direction: deltaTime < 0 ? - 1 : 1 } ); } } else { // repetitive Repeat or PingPong if ( loopCount === - 1 ) { // just started if ( deltaTime >= 0 ) { loopCount = 0; this._setEndings( true, this.repetitions === 0, pingPong ); } else { // when looping in reverse direction, the initial // transition through zero counts as a repetition, // so leave loopCount at -1 this._setEndings( this.repetitions === 0, true, pingPong ); } } if ( time >= duration || time < 0 ) { // wrap around var loopDelta = Math.floor( time / duration ); // signed time -= duration * loopDelta; loopCount += Math.abs( loopDelta ); var pending = this.repetitions - loopCount; if ( pending <= 0 ) { // have to stop (switch state, clamp time, fire event) if ( this.clampWhenFinished ) { this.paused = true; } else { this.enabled = false; } time = deltaTime > 0 ? duration : 0; this.time = time; this._mixer.dispatchEvent( { type: 'finished', action: this, direction: deltaTime > 0 ? 1 : - 1 } ); } else { // keep running if ( pending === 1 ) { // entering the last round var atStart = deltaTime < 0; this._setEndings( atStart, ! atStart, pingPong ); } else { this._setEndings( false, false, pingPong ); } this._loopCount = loopCount; this.time = time; this._mixer.dispatchEvent( { type: 'loop', action: this, loopDelta: loopDelta } ); } } else { this.time = time; } if ( pingPong && ( loopCount & 1 ) === 1 ) { // invert time for the "pong round" return duration - time; } } return time; }, _setEndings: function ( atStart, atEnd, pingPong ) { var settings = this._interpolantSettings; if ( pingPong ) { settings.endingStart = ZeroSlopeEnding; settings.endingEnd = ZeroSlopeEnding; } else { // assuming for LoopOnce atStart == atEnd == true if ( atStart ) { settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding; } else { settings.endingStart = WrapAroundEnding; } if ( atEnd ) { settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding; } else { settings.endingEnd = WrapAroundEnding; } } }, _scheduleFading: function ( duration, weightNow, weightThen ) { var mixer = this._mixer, now = mixer.time, interpolant = this._weightInterpolant; if ( interpolant === null ) { interpolant = mixer._lendControlInterpolant(); this._weightInterpolant = interpolant; } var times = interpolant.parameterPositions, values = interpolant.sampleValues; times[ 0 ] = now; values[ 0 ] = weightNow; times[ 1 ] = now + duration; values[ 1 ] = weightThen; return this; } } ); /** * * Player for AnimationClips. * * * @author Ben Houston / http://clara.io/ * @author David Sarno / http://lighthaus.us/ * @author tschw */ function AnimationMixer( root ) { this._root = root; this._initMemoryManager(); this._accuIndex = 0; this.time = 0; this.timeScale = 1.0; } AnimationMixer.prototype = Object.assign( Object.create( EventDispatcher.prototype ), { constructor: AnimationMixer, _bindAction: function ( action, prototypeAction ) { var root = action._localRoot || this._root, tracks = action._clip.tracks, nTracks = tracks.length, bindings = action._propertyBindings, interpolants = action._interpolants, rootUuid = root.uuid, bindingsByRoot = this._bindingsByRootAndName, bindingsByName = bindingsByRoot[ rootUuid ]; if ( bindingsByName === undefined ) { bindingsByName = {}; bindingsByRoot[ rootUuid ] = bindingsByName; } for ( var i = 0; i !== nTracks; ++ i ) { var track = tracks[ i ], trackName = track.name, binding = bindingsByName[ trackName ]; if ( binding !== undefined ) { bindings[ i ] = binding; } else { binding = bindings[ i ]; if ( binding !== undefined ) { // existing binding, make sure the cache knows if ( binding._cacheIndex === null ) { ++ binding.referenceCount; this._addInactiveBinding( binding, rootUuid, trackName ); } continue; } var path = prototypeAction && prototypeAction. _propertyBindings[ i ].binding.parsedPath; binding = new PropertyMixer( PropertyBinding.create( root, trackName, path ), track.ValueTypeName, track.getValueSize() ); ++ binding.referenceCount; this._addInactiveBinding( binding, rootUuid, trackName ); bindings[ i ] = binding; } interpolants[ i ].resultBuffer = binding.buffer; } }, _activateAction: function ( action ) { if ( ! this._isActiveAction( action ) ) { if ( action._cacheIndex === null ) { // this action has been forgotten by the cache, but the user // appears to be still using it -> rebind var rootUuid = ( action._localRoot || this._root ).uuid, clipUuid = action._clip.uuid, actionsForClip = this._actionsByClip[ clipUuid ]; this._bindAction( action, actionsForClip && actionsForClip.knownActions[ 0 ] ); this._addInactiveAction( action, clipUuid, rootUuid ); } var bindings = action._propertyBindings; // increment reference counts / sort out state for ( var i = 0, n = bindings.length; i !== n; ++ i ) { var binding = bindings[ i ]; if ( binding.useCount ++ === 0 ) { this._lendBinding( binding ); binding.saveOriginalState(); } } this._lendAction( action ); } }, _deactivateAction: function ( action ) { if ( this._isActiveAction( action ) ) { var bindings = action._propertyBindings; // decrement reference counts / sort out state for ( var i = 0, n = bindings.length; i !== n; ++ i ) { var binding = bindings[ i ]; if ( -- binding.useCount === 0 ) { binding.restoreOriginalState(); this._takeBackBinding( binding ); } } this._takeBackAction( action ); } }, // Memory manager _initMemoryManager: function () { this._actions = []; // 'nActiveActions' followed by inactive ones this._nActiveActions = 0; this._actionsByClip = {}; // inside: // { // knownActions: Array< AnimationAction > - used as prototypes // actionByRoot: AnimationAction - lookup // } this._bindings = []; // 'nActiveBindings' followed by inactive ones this._nActiveBindings = 0; this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer > this._controlInterpolants = []; // same game as above this._nActiveControlInterpolants = 0; var scope = this; this.stats = { actions: { get total() { return scope._actions.length; }, get inUse() { return scope._nActiveActions; } }, bindings: { get total() { return scope._bindings.length; }, get inUse() { return scope._nActiveBindings; } }, controlInterpolants: { get total() { return scope._controlInterpolants.length; }, get inUse() { return scope._nActiveControlInterpolants; } } }; }, // Memory management for AnimationAction objects _isActiveAction: function ( action ) { var index = action._cacheIndex; return index !== null && index < this._nActiveActions; }, _addInactiveAction: function ( action, clipUuid, rootUuid ) { var actions = this._actions, actionsByClip = this._actionsByClip, actionsForClip = actionsByClip[ clipUuid ]; if ( actionsForClip === undefined ) { actionsForClip = { knownActions: [ action ], actionByRoot: {} }; action._byClipCacheIndex = 0; actionsByClip[ clipUuid ] = actionsForClip; } else { var knownActions = actionsForClip.knownActions; action._byClipCacheIndex = knownActions.length; knownActions.push( action ); } action._cacheIndex = actions.length; actions.push( action ); actionsForClip.actionByRoot[ rootUuid ] = action; }, _removeInactiveAction: function ( action ) { var actions = this._actions, lastInactiveAction = actions[ actions.length - 1 ], cacheIndex = action._cacheIndex; lastInactiveAction._cacheIndex = cacheIndex; actions[ cacheIndex ] = lastInactiveAction; actions.pop(); action._cacheIndex = null; var clipUuid = action._clip.uuid, actionsByClip = this._actionsByClip, actionsForClip = actionsByClip[ clipUuid ], knownActionsForClip = actionsForClip.knownActions, lastKnownAction = knownActionsForClip[ knownActionsForClip.length - 1 ], byClipCacheIndex = action._byClipCacheIndex; lastKnownAction._byClipCacheIndex = byClipCacheIndex; knownActionsForClip[ byClipCacheIndex ] = lastKnownAction; knownActionsForClip.pop(); action._byClipCacheIndex = null; var actionByRoot = actionsForClip.actionByRoot, rootUuid = ( action._localRoot || this._root ).uuid; delete actionByRoot[ rootUuid ]; if ( knownActionsForClip.length === 0 ) { delete actionsByClip[ clipUuid ]; } this._removeInactiveBindingsForAction( action ); }, _removeInactiveBindingsForAction: function ( action ) { var bindings = action._propertyBindings; for ( var i = 0, n = bindings.length; i !== n; ++ i ) { var binding = bindings[ i ]; if ( -- binding.referenceCount === 0 ) { this._removeInactiveBinding( binding ); } } }, _lendAction: function ( action ) { // [ active actions | inactive actions ] // [ active actions >| inactive actions ] // s a // <-swap-> // a s var actions = this._actions, prevIndex = action._cacheIndex, lastActiveIndex = this._nActiveActions ++, firstInactiveAction = actions[ lastActiveIndex ]; action._cacheIndex = lastActiveIndex; actions[ lastActiveIndex ] = action; firstInactiveAction._cacheIndex = prevIndex; actions[ prevIndex ] = firstInactiveAction; }, _takeBackAction: function ( action ) { // [ active actions | inactive actions ] // [ active actions |< inactive actions ] // a s // <-swap-> // s a var actions = this._actions, prevIndex = action._cacheIndex, firstInactiveIndex = -- this._nActiveActions, lastActiveAction = actions[ firstInactiveIndex ]; action._cacheIndex = firstInactiveIndex; actions[ firstInactiveIndex ] = action; lastActiveAction._cacheIndex = prevIndex; actions[ prevIndex ] = lastActiveAction; }, // Memory management for PropertyMixer objects _addInactiveBinding: function ( binding, rootUuid, trackName ) { var bindingsByRoot = this._bindingsByRootAndName, bindingByName = bindingsByRoot[ rootUuid ], bindings = this._bindings; if ( bindingByName === undefined ) { bindingByName = {}; bindingsByRoot[ rootUuid ] = bindingByName; } bindingByName[ trackName ] = binding; binding._cacheIndex = bindings.length; bindings.push( binding ); }, _removeInactiveBinding: function ( binding ) { var bindings = this._bindings, propBinding = binding.binding, rootUuid = propBinding.rootNode.uuid, trackName = propBinding.path, bindingsByRoot = this._bindingsByRootAndName, bindingByName = bindingsByRoot[ rootUuid ], lastInactiveBinding = bindings[ bindings.length - 1 ], cacheIndex = binding._cacheIndex; lastInactiveBinding._cacheIndex = cacheIndex; bindings[ cacheIndex ] = lastInactiveBinding; bindings.pop(); delete bindingByName[ trackName ]; if ( Object.keys( bindingByName ).length === 0 ) { delete bindingsByRoot[ rootUuid ]; } }, _lendBinding: function ( binding ) { var bindings = this._bindings, prevIndex = binding._cacheIndex, lastActiveIndex = this._nActiveBindings ++, firstInactiveBinding = bindings[ lastActiveIndex ]; binding._cacheIndex = lastActiveIndex; bindings[ lastActiveIndex ] = binding; firstInactiveBinding._cacheIndex = prevIndex; bindings[ prevIndex ] = firstInactiveBinding; }, _takeBackBinding: function ( binding ) { var bindings = this._bindings, prevIndex = binding._cacheIndex, firstInactiveIndex = -- this._nActiveBindings, lastActiveBinding = bindings[ firstInactiveIndex ]; binding._cacheIndex = firstInactiveIndex; bindings[ firstInactiveIndex ] = binding; lastActiveBinding._cacheIndex = prevIndex; bindings[ prevIndex ] = lastActiveBinding; }, // Memory management of Interpolants for weight and time scale _lendControlInterpolant: function () { var interpolants = this._controlInterpolants, lastActiveIndex = this._nActiveControlInterpolants ++, interpolant = interpolants[ lastActiveIndex ]; if ( interpolant === undefined ) { interpolant = new LinearInterpolant( new Float32Array( 2 ), new Float32Array( 2 ), 1, this._controlInterpolantsResultBuffer ); interpolant.__cacheIndex = lastActiveIndex; interpolants[ lastActiveIndex ] = interpolant; } return interpolant; }, _takeBackControlInterpolant: function ( interpolant ) { var interpolants = this._controlInterpolants, prevIndex = interpolant.__cacheIndex, firstInactiveIndex = -- this._nActiveControlInterpolants, lastActiveInterpolant = interpolants[ firstInactiveIndex ]; interpolant.__cacheIndex = firstInactiveIndex; interpolants[ firstInactiveIndex ] = interpolant; lastActiveInterpolant.__cacheIndex = prevIndex; interpolants[ prevIndex ] = lastActiveInterpolant; }, _controlInterpolantsResultBuffer: new Float32Array( 1 ), // return an action for a clip optionally using a custom root target // object (this method allocates a lot of dynamic memory in case a // previously unknown clip/root combination is specified) clipAction: function ( clip, optionalRoot ) { var root = optionalRoot || this._root, rootUuid = root.uuid, clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip, clipUuid = clipObject !== null ? clipObject.uuid : clip, actionsForClip = this._actionsByClip[ clipUuid ], prototypeAction = null; if ( actionsForClip !== undefined ) { var existingAction = actionsForClip.actionByRoot[ rootUuid ]; if ( existingAction !== undefined ) { return existingAction; } // we know the clip, so we don't have to parse all // the bindings again but can just copy prototypeAction = actionsForClip.knownActions[ 0 ]; // also, take the clip from the prototype action if ( clipObject === null ) { clipObject = prototypeAction._clip; } } // clip must be known when specified via string if ( clipObject === null ) { return null; } // allocate all resources required to run it var newAction = new AnimationAction( this, clipObject, optionalRoot ); this._bindAction( newAction, prototypeAction ); // and make the action known to the memory manager this._addInactiveAction( newAction, clipUuid, rootUuid ); return newAction; }, // get an existing action existingAction: function ( clip, optionalRoot ) { var root = optionalRoot || this._root, rootUuid = root.uuid, clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip, clipUuid = clipObject ? clipObject.uuid : clip, actionsForClip = this._actionsByClip[ clipUuid ]; if ( actionsForClip !== undefined ) { return actionsForClip.actionByRoot[ rootUuid ] || null; } return null; }, // deactivates all previously scheduled actions stopAllAction: function () { var actions = this._actions, nActions = this._nActiveActions, bindings = this._bindings, nBindings = this._nActiveBindings; this._nActiveActions = 0; this._nActiveBindings = 0; for ( var i = 0; i !== nActions; ++ i ) { actions[ i ].reset(); } for ( var i = 0; i !== nBindings; ++ i ) { bindings[ i ].useCount = 0; } return this; }, // advance the time and update apply the animation update: function ( deltaTime ) { deltaTime *= this.timeScale; var actions = this._actions, nActions = this._nActiveActions, time = this.time += deltaTime, timeDirection = Math.sign( deltaTime ), accuIndex = this._accuIndex ^= 1; // run active actions for ( var i = 0; i !== nActions; ++ i ) { var action = actions[ i ]; action._update( time, deltaTime, timeDirection, accuIndex ); } // update scene graph var bindings = this._bindings, nBindings = this._nActiveBindings; for ( var i = 0; i !== nBindings; ++ i ) { bindings[ i ].apply( accuIndex ); } return this; }, // Allows you to seek to a specific time in an animation. setTime: function ( timeInSeconds ) { this.time = 0; // Zero out time attribute for AnimationMixer object; for ( var i = 0; i < this._actions.length; i ++ ) { this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects. } return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object. }, // return this mixer's root target object getRoot: function () { return this._root; }, // free all resources specific to a particular clip uncacheClip: function ( clip ) { var actions = this._actions, clipUuid = clip.uuid, actionsByClip = this._actionsByClip, actionsForClip = actionsByClip[ clipUuid ]; if ( actionsForClip !== undefined ) { // note: just calling _removeInactiveAction would mess up the // iteration state and also require updating the state we can // just throw away var actionsToRemove = actionsForClip.knownActions; for ( var i = 0, n = actionsToRemove.length; i !== n; ++ i ) { var action = actionsToRemove[ i ]; this._deactivateAction( action ); var cacheIndex = action._cacheIndex, lastInactiveAction = actions[ actions.length - 1 ]; action._cacheIndex = null; action._byClipCacheIndex = null; lastInactiveAction._cacheIndex = cacheIndex; actions[ cacheIndex ] = lastInactiveAction; actions.pop(); this._removeInactiveBindingsForAction( action ); } delete actionsByClip[ clipUuid ]; } }, // free all resources specific to a particular root target object uncacheRoot: function ( root ) { var rootUuid = root.uuid, actionsByClip = this._actionsByClip; for ( var clipUuid in actionsByClip ) { var actionByRoot = actionsByClip[ clipUuid ].actionByRoot, action = actionByRoot[ rootUuid ]; if ( action !== undefined ) { this._deactivateAction( action ); this._removeInactiveAction( action ); } } var bindingsByRoot = this._bindingsByRootAndName, bindingByName = bindingsByRoot[ rootUuid ]; if ( bindingByName !== undefined ) { for ( var trackName in bindingByName ) { var binding = bindingByName[ trackName ]; binding.restoreOriginalState(); this._removeInactiveBinding( binding ); } } }, // remove a targeted clip from the cache uncacheAction: function ( clip, optionalRoot ) { var action = this.existingAction( clip, optionalRoot ); if ( action !== null ) { this._deactivateAction( action ); this._removeInactiveAction( action ); } } } ); /** * @author mrdoob / http://mrdoob.com/ */ function Uniform( value ) { if ( typeof value === 'string' ) { console.warn( 'THREE.Uniform: Type parameter is no longer needed.' ); value = arguments[ 1 ]; } this.value = value; } Uniform.prototype.clone = function () { return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() ); }; /** * @author benaadams / https://twitter.com/ben_a_adams */ function InstancedInterleavedBuffer( array, stride, meshPerAttribute ) { InterleavedBuffer.call( this, array, stride ); this.meshPerAttribute = meshPerAttribute || 1; } InstancedInterleavedBuffer.prototype = Object.assign( Object.create( InterleavedBuffer.prototype ), { constructor: InstancedInterleavedBuffer, isInstancedInterleavedBuffer: true, copy: function ( source ) { InterleavedBuffer.prototype.copy.call( this, source ); this.meshPerAttribute = source.meshPerAttribute; return this; } } ); /** * @author mrdoob / http://mrdoob.com/ * @author bhouston / http://clara.io/ * @author stephomi / http://stephaneginier.com/ */ function Raycaster( origin, direction, near, far ) { this.ray = new Ray( origin, direction ); // direction is assumed to be normalized (for accurate distance calculations) this.near = near || 0; this.far = far || Infinity; this.camera = null; this.params = { Mesh: {}, Line: {}, LOD: {}, Points: { threshold: 1 }, Sprite: {} }; Object.defineProperties( this.params, { PointCloud: { get: function () { console.warn( 'THREE.Raycaster: params.PointCloud has been renamed to params.Points.' ); return this.Points; } } } ); } function ascSort( a, b ) { return a.distance - b.distance; } function intersectObject( object, raycaster, intersects, recursive ) { if ( object.visible === false ) { return; } object.raycast( raycaster, intersects ); if ( recursive === true ) { var children = object.children; for ( var i = 0, l = children.length; i < l; i ++ ) { intersectObject( children[ i ], raycaster, intersects, true ); } } } Object.assign( Raycaster.prototype, { linePrecision: 1, set: function ( origin, direction ) { // direction is assumed to be normalized (for accurate distance calculations) this.ray.set( origin, direction ); }, setFromCamera: function ( coords, camera ) { if ( ( camera && camera.isPerspectiveCamera ) ) { this.ray.origin.setFromMatrixPosition( camera.matrixWorld ); this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize(); this.camera = camera; } else if ( ( camera && camera.isOrthographicCamera ) ) { this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld ); this.camera = camera; } else { console.error( 'THREE.Raycaster: Unsupported camera type.' ); } }, intersectObject: function ( object, recursive, optionalTarget ) { var intersects = optionalTarget || []; intersectObject( object, this, intersects, recursive ); intersects.sort( ascSort ); return intersects; }, intersectObjects: function ( objects, recursive, optionalTarget ) { var intersects = optionalTarget || []; if ( Array.isArray( objects ) === false ) { console.warn( 'THREE.Raycaster.intersectObjects: objects is not an Array.' ); return intersects; } for ( var i = 0, l = objects.length; i < l; i ++ ) { intersectObject( objects[ i ], this, intersects, recursive ); } intersects.sort( ascSort ); return intersects; } } ); /** * @author bhouston / http://clara.io * @author WestLangley / http://github.com/WestLangley * * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system * * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up. * The azimuthal angle (theta) is measured from the positive z-axis. */ function Spherical( radius, phi, theta ) { this.radius = ( radius !== undefined ) ? radius : 1.0; this.phi = ( phi !== undefined ) ? phi : 0; // polar angle this.theta = ( theta !== undefined ) ? theta : 0; // azimuthal angle return this; } Object.assign( Spherical.prototype, { set: function ( radius, phi, theta ) { this.radius = radius; this.phi = phi; this.theta = theta; return this; }, clone: function () { return new this.constructor().copy( this ); }, copy: function ( other ) { this.radius = other.radius; this.phi = other.phi; this.theta = other.theta; return this; }, // restrict phi to be betwee EPS and PI-EPS makeSafe: function () { var EPS = 0.000001; this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) ); return this; }, setFromVector3: function ( v ) { return this.setFromCartesianCoords( v.x, v.y, v.z ); }, setFromCartesianCoords: function ( x, y, z ) { this.radius = Math.sqrt( x * x + y * y + z * z ); if ( this.radius === 0 ) { this.theta = 0; this.phi = 0; } else { this.theta = Math.atan2( x, z ); this.phi = Math.acos( MathUtils.clamp( y / this.radius, - 1, 1 ) ); } return this; } } ); /** * @author Mugen87 / https://github.com/Mugen87 * * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system * */ function Cylindrical( radius, theta, y ) { this.radius = ( radius !== undefined ) ? radius : 1.0; // distance from the origin to a point in the x-z plane this.theta = ( theta !== undefined ) ? theta : 0; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis this.y = ( y !== undefined ) ? y : 0; // height above the x-z plane return this; } Object.assign( Cylindrical.prototype, { set: function ( radius, theta, y ) { this.radius = radius; this.theta = theta; this.y = y; return this; }, clone: function () { return new this.constructor().copy( this ); }, copy: function ( other ) { this.radius = other.radius; this.theta = other.theta; this.y = other.y; return this; }, setFromVector3: function ( v ) { return this.setFromCartesianCoords( v.x, v.y, v.z ); }, setFromCartesianCoords: function ( x, y, z ) { this.radius = Math.sqrt( x * x + z * z ); this.theta = Math.atan2( x, z ); this.y = y; return this; } } ); /** * @author bhouston / http://clara.io */ var _vector$7 = new Vector2(); function Box2( min, max ) { this.min = ( min !== undefined ) ? min : new Vector2( + Infinity, + Infinity ); this.max = ( max !== undefined ) ? max : new Vector2( - Infinity, - Infinity ); } Object.assign( Box2.prototype, { set: function ( min, max ) { this.min.copy( min ); this.max.copy( max ); return this; }, setFromPoints: function ( points ) { this.makeEmpty(); for ( var i = 0, il = points.length; i < il; i ++ ) { this.expandByPoint( points[ i ] ); } return this; }, setFromCenterAndSize: function ( center, size ) { var halfSize = _vector$7.copy( size ).multiplyScalar( 0.5 ); this.min.copy( center ).sub( halfSize ); this.max.copy( center ).add( halfSize ); return this; }, clone: function () { return new this.constructor().copy( this ); }, copy: function ( box ) { this.min.copy( box.min ); this.max.copy( box.max ); return this; }, makeEmpty: function () { this.min.x = this.min.y = + Infinity; this.max.x = this.max.y = - Infinity; return this; }, isEmpty: function () { // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ); }, getCenter: function ( target ) { if ( target === undefined ) { console.warn( 'THREE.Box2: .getCenter() target is now required' ); target = new Vector2(); } return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 ); }, getSize: function ( target ) { if ( target === undefined ) { console.warn( 'THREE.Box2: .getSize() target is now required' ); target = new Vector2(); } return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min ); }, expandByPoint: function ( point ) { this.min.min( point ); this.max.max( point ); return this; }, expandByVector: function ( vector ) { this.min.sub( vector ); this.max.add( vector ); return this; }, expandByScalar: function ( scalar ) { this.min.addScalar( - scalar ); this.max.addScalar( scalar ); return this; }, containsPoint: function ( point ) { return point.x < this.min.x || point.x > this.max.x || point.y < this.min.y || point.y > this.max.y ? false : true; }, containsBox: function ( box ) { return this.min.x <= box.min.x && box.max.x <= this.max.x && this.min.y <= box.min.y && box.max.y <= this.max.y; }, getParameter: function ( point, target ) { // This can potentially have a divide by zero if the box // has a size dimension of 0. if ( target === undefined ) { console.warn( 'THREE.Box2: .getParameter() target is now required' ); target = new Vector2(); } return target.set( ( point.x - this.min.x ) / ( this.max.x - this.min.x ), ( point.y - this.min.y ) / ( this.max.y - this.min.y ) ); }, intersectsBox: function ( box ) { // using 4 splitting planes to rule out intersections return box.max.x < this.min.x || box.min.x > this.max.x || box.max.y < this.min.y || box.min.y > this.max.y ? false : true; }, clampPoint: function ( point, target ) { if ( target === undefined ) { console.warn( 'THREE.Box2: .clampPoint() target is now required' ); target = new Vector2(); } return target.copy( point ).clamp( this.min, this.max ); }, distanceToPoint: function ( point ) { var clampedPoint = _vector$7.copy( point ).clamp( this.min, this.max ); return clampedPoint.sub( point ).length(); }, intersect: function ( box ) { this.min.max( box.min ); this.max.min( box.max ); return this; }, union: function ( box ) { this.min.min( box.min ); this.max.max( box.max ); return this; }, translate: function ( offset ) { this.min.add( offset ); this.max.add( offset ); return this; }, equals: function ( box ) { return box.min.equals( this.min ) && box.max.equals( this.max ); } } ); /** * @author bhouston / http://clara.io */ var _startP = new Vector3(); var _startEnd = new Vector3(); function Line3( start, end ) { this.start = ( start !== undefined ) ? start : new Vector3(); this.end = ( end !== undefined ) ? end : new Vector3(); } Object.assign( Line3.prototype, { set: function ( start, end ) { this.start.copy( start ); this.end.copy( end ); return this; }, clone: function () { return new this.constructor().copy( this ); }, copy: function ( line ) { this.start.copy( line.start ); this.end.copy( line.end ); return this; }, getCenter: function ( target ) { if ( target === undefined ) { console.warn( 'THREE.Line3: .getCenter() target is now required' ); target = new Vector3(); } return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 ); }, delta: function ( target ) { if ( target === undefined ) { console.warn( 'THREE.Line3: .delta() target is now required' ); target = new Vector3(); } return target.subVectors( this.end, this.start ); }, distanceSq: function () { return this.start.distanceToSquared( this.end ); }, distance: function () { return this.start.distanceTo( this.end ); }, at: function ( t, target ) { if ( target === undefined ) { console.warn( 'THREE.Line3: .at() target is now required' ); target = new Vector3(); } return this.delta( target ).multiplyScalar( t ).add( this.start ); }, closestPointToPointParameter: function ( point, clampToLine ) { _startP.subVectors( point, this.start ); _startEnd.subVectors( this.end, this.start ); var startEnd2 = _startEnd.dot( _startEnd ); var startEnd_startP = _startEnd.dot( _startP ); var t = startEnd_startP / startEnd2; if ( clampToLine ) { t = MathUtils.clamp( t, 0, 1 ); } return t; }, closestPointToPoint: function ( point, clampToLine, target ) { var t = this.closestPointToPointParameter( point, clampToLine ); if ( target === undefined ) { console.warn( 'THREE.Line3: .closestPointToPoint() target is now required' ); target = new Vector3(); } return this.delta( target ).multiplyScalar( t ).add( this.start ); }, applyMatrix4: function ( matrix ) { this.start.applyMatrix4( matrix ); this.end.applyMatrix4( matrix ); return this; }, equals: function ( line ) { return line.start.equals( this.start ) && line.end.equals( this.end ); } } ); /** * @author alteredq / http://alteredqualia.com/ */ function ImmediateRenderObject( material ) { Object3D.call( this ); this.material = material; this.render = function ( /* renderCallback */ ) {}; } ImmediateRenderObject.prototype = Object.create( Object3D.prototype ); ImmediateRenderObject.prototype.constructor = ImmediateRenderObject; ImmediateRenderObject.prototype.isImmediateRenderObject = true; /** * @author alteredq / http://alteredqualia.com/ * @author mrdoob / http://mrdoob.com/ * @author WestLangley / http://github.com/WestLangley */ var _vector$8 = new Vector3(); function SpotLightHelper( light, color ) { Object3D.call( this ); this.light = light; this.light.updateMatrixWorld(); this.matrix = light.matrixWorld; this.matrixAutoUpdate = false; this.color = color; var geometry = new BufferGeometry(); var positions = [ 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, - 1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, - 1, 1 ]; for ( var i = 0, j = 1, l = 32; i < l; i ++, j ++ ) { var p1 = ( i / l ) * Math.PI * 2; var p2 = ( j / l ) * Math.PI * 2; positions.push( Math.cos( p1 ), Math.sin( p1 ), 1, Math.cos( p2 ), Math.sin( p2 ), 1 ); } geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) ); var material = new LineBasicMaterial( { fog: false } ); this.cone = new LineSegments( geometry, material ); this.add( this.cone ); this.update(); } SpotLightHelper.prototype = Object.create( Object3D.prototype ); SpotLightHelper.prototype.constructor = SpotLightHelper; SpotLightHelper.prototype.dispose = function () { this.cone.geometry.dispose(); this.cone.material.dispose(); }; SpotLightHelper.prototype.update = function () { this.light.updateMatrixWorld(); var coneLength = this.light.distance ? this.light.distance : 1000; var coneWidth = coneLength * Math.tan( this.light.angle ); this.cone.scale.set( coneWidth, coneWidth, coneLength ); _vector$8.setFromMatrixPosition( this.light.target.matrixWorld ); this.cone.lookAt( _vector$8 ); if ( this.color !== undefined ) { this.cone.material.color.set( this.color ); } else { this.cone.material.color.copy( this.light.color ); } }; /** * @author Sean Griffin / http://twitter.com/sgrif * @author Michael Guerrero / http://realitymeltdown.com * @author mrdoob / http://mrdoob.com/ * @author ikerr / http://verold.com * @author Mugen87 / https://github.com/Mugen87 */ var _vector$9 = new Vector3(); var _boneMatrix = new Matrix4(); var _matrixWorldInv = new Matrix4(); function getBoneList( object ) { var boneList = []; if ( object && object.isBone ) { boneList.push( object ); } for ( var i = 0; i < object.children.length; i ++ ) { boneList.push.apply( boneList, getBoneList( object.children[ i ] ) ); } return boneList; } function SkeletonHelper( object ) { var bones = getBoneList( object ); var geometry = new BufferGeometry(); var vertices = []; var colors = []; var color1 = new Color( 0, 0, 1 ); var color2 = new Color( 0, 1, 0 ); for ( var i = 0; i < bones.length; i ++ ) { var bone = bones[ i ]; if ( bone.parent && bone.parent.isBone ) { vertices.push( 0, 0, 0 ); vertices.push( 0, 0, 0 ); colors.push( color1.r, color1.g, color1.b ); colors.push( color2.r, color2.g, color2.b ); } } geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) ); var material = new LineBasicMaterial( { vertexColors: VertexColors, depthTest: false, depthWrite: false, transparent: true } ); LineSegments.call( this, geometry, material ); this.root = object; this.bones = bones; this.matrix = object.matrixWorld; this.matrixAutoUpdate = false; } SkeletonHelper.prototype = Object.create( LineSegments.prototype ); SkeletonHelper.prototype.constructor = SkeletonHelper; SkeletonHelper.prototype.updateMatrixWorld = function ( force ) { var bones = this.bones; var geometry = this.geometry; var position = geometry.getAttribute( 'position' ); _matrixWorldInv.getInverse( this.root.matrixWorld ); for ( var i = 0, j = 0; i < bones.length; i ++ ) { var bone = bones[ i ]; if ( bone.parent && bone.parent.isBone ) { _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld ); _vector$9.setFromMatrixPosition( _boneMatrix ); position.setXYZ( j, _vector$9.x, _vector$9.y, _vector$9.z ); _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld ); _vector$9.setFromMatrixPosition( _boneMatrix ); position.setXYZ( j + 1, _vector$9.x, _vector$9.y, _vector$9.z ); j += 2; } } geometry.getAttribute( 'position' ).needsUpdate = true; Object3D.prototype.updateMatrixWorld.call( this, force ); }; /** * @author alteredq / http://alteredqualia.com/ * @author mrdoob / http://mrdoob.com/ */ function PointLightHelper( light, sphereSize, color ) { this.light = light; this.light.updateMatrixWorld(); this.color = color; var geometry = new SphereBufferGeometry( sphereSize, 4, 2 ); var material = new MeshBasicMaterial( { wireframe: true, fog: false } ); Mesh.call( this, geometry, material ); this.matrix = this.light.matrixWorld; this.matrixAutoUpdate = false; this.update(); /* var distanceGeometry = new THREE.IcosahedronBufferGeometry( 1, 2 ); var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } ); this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial ); this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial ); var d = light.distance; if ( d === 0.0 ) { this.lightDistance.visible = false; } else { this.lightDistance.scale.set( d, d, d ); } this.add( this.lightDistance ); */ } PointLightHelper.prototype = Object.create( Mesh.prototype ); PointLightHelper.prototype.constructor = PointLightHelper; PointLightHelper.prototype.dispose = function () { this.geometry.dispose(); this.material.dispose(); }; PointLightHelper.prototype.update = function () { if ( this.color !== undefined ) { this.material.color.set( this.color ); } else { this.material.color.copy( this.light.color ); } /* var d = this.light.distance; if ( d === 0.0 ) { this.lightDistance.visible = false; } else { this.lightDistance.visible = true; this.lightDistance.scale.set( d, d, d ); } */ }; /** * @author alteredq / http://alteredqualia.com/ * @author mrdoob / http://mrdoob.com/ * @author Mugen87 / https://github.com/Mugen87 */ var _vector$a = new Vector3(); var _color1 = new Color(); var _color2 = new Color(); function HemisphereLightHelper( light, size, color ) { Object3D.call( this ); this.light = light; this.light.updateMatrixWorld(); this.matrix = light.matrixWorld; this.matrixAutoUpdate = false; this.color = color; var geometry = new OctahedronBufferGeometry( size ); geometry.rotateY( Math.PI * 0.5 ); this.material = new MeshBasicMaterial( { wireframe: true, fog: false } ); if ( this.color === undefined ) { this.material.vertexColors = VertexColors; } var position = geometry.getAttribute( 'position' ); var colors = new Float32Array( position.count * 3 ); geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) ); this.add( new Mesh( geometry, this.material ) ); this.update(); } HemisphereLightHelper.prototype = Object.create( Object3D.prototype ); HemisphereLightHelper.prototype.constructor = HemisphereLightHelper; HemisphereLightHelper.prototype.dispose = function () { this.children[ 0 ].geometry.dispose(); this.children[ 0 ].material.dispose(); }; HemisphereLightHelper.prototype.update = function () { var mesh = this.children[ 0 ]; if ( this.color !== undefined ) { this.material.color.set( this.color ); } else { var colors = mesh.geometry.getAttribute( 'color' ); _color1.copy( this.light.color ); _color2.copy( this.light.groundColor ); for ( var i = 0, l = colors.count; i < l; i ++ ) { var color = ( i < ( l / 2 ) ) ? _color1 : _color2; colors.setXYZ( i, color.r, color.g, color.b ); } colors.needsUpdate = true; } mesh.lookAt( _vector$a.setFromMatrixPosition( this.light.matrixWorld ).negate() ); }; /** * @author mrdoob / http://mrdoob.com/ */ function GridHelper( size, divisions, color1, color2 ) { size = size || 10; divisions = divisions || 10; color1 = new Color( color1 !== undefined ? color1 : 0x444444 ); color2 = new Color( color2 !== undefined ? color2 : 0x888888 ); var center = divisions / 2; var step = size / divisions; var halfSize = size / 2; var vertices = [], colors = []; for ( var i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) { vertices.push( - halfSize, 0, k, halfSize, 0, k ); vertices.push( k, 0, - halfSize, k, 0, halfSize ); var color = i === center ? color1 : color2; color.toArray( colors, j ); j += 3; color.toArray( colors, j ); j += 3; color.toArray( colors, j ); j += 3; color.toArray( colors, j ); j += 3; } var geometry = new BufferGeometry(); geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) ); var material = new LineBasicMaterial( { vertexColors: VertexColors } ); LineSegments.call( this, geometry, material ); } GridHelper.prototype = Object.assign( Object.create( LineSegments.prototype ), { constructor: GridHelper, copy: function ( source ) { LineSegments.prototype.copy.call( this, source ); this.geometry.copy( source.geometry ); this.material.copy( source.material ); return this; }, clone: function () { return new this.constructor().copy( this ); } } ); /** * @author mrdoob / http://mrdoob.com/ * @author Mugen87 / http://github.com/Mugen87 * @author Hectate / http://www.github.com/Hectate */ function PolarGridHelper( radius, radials, circles, divisions, color1, color2 ) { radius = radius || 10; radials = radials || 16; circles = circles || 8; divisions = divisions || 64; color1 = new Color( color1 !== undefined ? color1 : 0x444444 ); color2 = new Color( color2 !== undefined ? color2 : 0x888888 ); var vertices = []; var colors = []; var x, z; var v, i, j, r, color; // create the radials for ( i = 0; i <= radials; i ++ ) { v = ( i / radials ) * ( Math.PI * 2 ); x = Math.sin( v ) * radius; z = Math.cos( v ) * radius; vertices.push( 0, 0, 0 ); vertices.push( x, 0, z ); color = ( i & 1 ) ? color1 : color2; colors.push( color.r, color.g, color.b ); colors.push( color.r, color.g, color.b ); } // create the circles for ( i = 0; i <= circles; i ++ ) { color = ( i & 1 ) ? color1 : color2; r = radius - ( radius / circles * i ); for ( j = 0; j < divisions; j ++ ) { // first vertex v = ( j / divisions ) * ( Math.PI * 2 ); x = Math.sin( v ) * r; z = Math.cos( v ) * r; vertices.push( x, 0, z ); colors.push( color.r, color.g, color.b ); // second vertex v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 ); x = Math.sin( v ) * r; z = Math.cos( v ) * r; vertices.push( x, 0, z ); colors.push( color.r, color.g, color.b ); } } var geometry = new BufferGeometry(); geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) ); var material = new LineBasicMaterial( { vertexColors: VertexColors } ); LineSegments.call( this, geometry, material ); } PolarGridHelper.prototype = Object.create( LineSegments.prototype ); PolarGridHelper.prototype.constructor = PolarGridHelper; /** * @author alteredq / http://alteredqualia.com/ * @author mrdoob / http://mrdoob.com/ * @author WestLangley / http://github.com/WestLangley */ var _v1$5 = new Vector3(); var _v2$3 = new Vector3(); var _v3$1 = new Vector3(); function DirectionalLightHelper( light, size, color ) { Object3D.call( this ); this.light = light; this.light.updateMatrixWorld(); this.matrix = light.matrixWorld; this.matrixAutoUpdate = false; this.color = color; if ( size === undefined ) { size = 1; } var geometry = new BufferGeometry(); geometry.setAttribute( 'position', new Float32BufferAttribute( [ - size, size, 0, size, size, 0, size, - size, 0, - size, - size, 0, - size, size, 0 ], 3 ) ); var material = new LineBasicMaterial( { fog: false } ); this.lightPlane = new Line( geometry, material ); this.add( this.lightPlane ); geometry = new BufferGeometry(); geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) ); this.targetLine = new Line( geometry, material ); this.add( this.targetLine ); this.update(); } DirectionalLightHelper.prototype = Object.create( Object3D.prototype ); DirectionalLightHelper.prototype.constructor = DirectionalLightHelper; DirectionalLightHelper.prototype.dispose = function () { this.lightPlane.geometry.dispose(); this.lightPlane.material.dispose(); this.targetLine.geometry.dispose(); this.targetLine.material.dispose(); }; DirectionalLightHelper.prototype.update = function () { _v1$5.setFromMatrixPosition( this.light.matrixWorld ); _v2$3.setFromMatrixPosition( this.light.target.matrixWorld ); _v3$1.subVectors( _v2$3, _v1$5 ); this.lightPlane.lookAt( _v2$3 ); if ( this.color !== undefined ) { this.lightPlane.material.color.set( this.color ); this.targetLine.material.color.set( this.color ); } else { this.lightPlane.material.color.copy( this.light.color ); this.targetLine.material.color.copy( this.light.color ); } this.targetLine.lookAt( _v2$3 ); this.targetLine.scale.z = _v3$1.length(); }; /** * @author alteredq / http://alteredqualia.com/ * @author Mugen87 / https://github.com/Mugen87 * * - shows frustum, line of sight and up of the camera * - suitable for fast updates * - based on frustum visualization in lightgl.js shadowmap example * http://evanw.github.com/lightgl.js/tests/shadowmap.html */ var _vector$b = new Vector3(); var _camera = new Camera(); function CameraHelper( camera ) { var geometry = new BufferGeometry(); var material = new LineBasicMaterial( { color: 0xffffff, vertexColors: FaceColors } ); var vertices = []; var colors = []; var pointMap = {}; // colors var colorFrustum = new Color( 0xffaa00 ); var colorCone = new Color( 0xff0000 ); var colorUp = new Color( 0x00aaff ); var colorTarget = new Color( 0xffffff ); var colorCross = new Color( 0x333333 ); // near addLine( 'n1', 'n2', colorFrustum ); addLine( 'n2', 'n4', colorFrustum ); addLine( 'n4', 'n3', colorFrustum ); addLine( 'n3', 'n1', colorFrustum ); // far addLine( 'f1', 'f2', colorFrustum ); addLine( 'f2', 'f4', colorFrustum ); addLine( 'f4', 'f3', colorFrustum ); addLine( 'f3', 'f1', colorFrustum ); // sides addLine( 'n1', 'f1', colorFrustum ); addLine( 'n2', 'f2', colorFrustum ); addLine( 'n3', 'f3', colorFrustum ); addLine( 'n4', 'f4', colorFrustum ); // cone addLine( 'p', 'n1', colorCone ); addLine( 'p', 'n2', colorCone ); addLine( 'p', 'n3', colorCone ); addLine( 'p', 'n4', colorCone ); // up addLine( 'u1', 'u2', colorUp ); addLine( 'u2', 'u3', colorUp ); addLine( 'u3', 'u1', colorUp ); // target addLine( 'c', 't', colorTarget ); addLine( 'p', 'c', colorCross ); // cross addLine( 'cn1', 'cn2', colorCross ); addLine( 'cn3', 'cn4', colorCross ); addLine( 'cf1', 'cf2', colorCross ); addLine( 'cf3', 'cf4', colorCross ); function addLine( a, b, color ) { addPoint( a, color ); addPoint( b, color ); } function addPoint( id, color ) { vertices.push( 0, 0, 0 ); colors.push( color.r, color.g, color.b ); if ( pointMap[ id ] === undefined ) { pointMap[ id ] = []; } pointMap[ id ].push( ( vertices.length / 3 ) - 1 ); } geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) ); LineSegments.call( this, geometry, material ); this.camera = camera; if ( this.camera.updateProjectionMatrix ) { this.camera.updateProjectionMatrix(); } this.matrix = camera.matrixWorld; this.matrixAutoUpdate = false; this.pointMap = pointMap; this.update(); } CameraHelper.prototype = Object.create( LineSegments.prototype ); CameraHelper.prototype.constructor = CameraHelper; CameraHelper.prototype.update = function () { var geometry = this.geometry; var pointMap = this.pointMap; var w = 1, h = 1; // we need just camera projection matrix inverse // world matrix must be identity _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse ); // center / target setPoint( 'c', pointMap, geometry, _camera, 0, 0, - 1 ); setPoint( 't', pointMap, geometry, _camera, 0, 0, 1 ); // near setPoint( 'n1', pointMap, geometry, _camera, - w, - h, - 1 ); setPoint( 'n2', pointMap, geometry, _camera, w, - h, - 1 ); setPoint( 'n3', pointMap, geometry, _camera, - w, h, - 1 ); setPoint( 'n4', pointMap, geometry, _camera, w, h, - 1 ); // far setPoint( 'f1', pointMap, geometry, _camera, - w, - h, 1 ); setPoint( 'f2', pointMap, geometry, _camera, w, - h, 1 ); setPoint( 'f3', pointMap, geometry, _camera, - w, h, 1 ); setPoint( 'f4', pointMap, geometry, _camera, w, h, 1 ); // up setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, - 1 ); setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, - 1 ); setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, - 1 ); // cross setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, 1 ); setPoint( 'cf2', pointMap, geometry, _camera, w, 0, 1 ); setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, 1 ); setPoint( 'cf4', pointMap, geometry, _camera, 0, h, 1 ); setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, - 1 ); setPoint( 'cn2', pointMap, geometry, _camera, w, 0, - 1 ); setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, - 1 ); setPoint( 'cn4', pointMap, geometry, _camera, 0, h, - 1 ); geometry.getAttribute( 'position' ).needsUpdate = true; }; function setPoint( point, pointMap, geometry, camera, x, y, z ) { _vector$b.set( x, y, z ).unproject( camera ); var points = pointMap[ point ]; if ( points !== undefined ) { var position = geometry.getAttribute( 'position' ); for ( var i = 0, l = points.length; i < l; i ++ ) { position.setXYZ( points[ i ], _vector$b.x, _vector$b.y, _vector$b.z ); } } } /** * @author mrdoob / http://mrdoob.com/ * @author Mugen87 / http://github.com/Mugen87 */ var _box$3 = new Box3(); function BoxHelper( object, color ) { this.object = object; if ( color === undefined ) { color = 0xffff00; } var indices = new Uint16Array( [ 0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7 ] ); var positions = new Float32Array( 8 * 3 ); var geometry = new BufferGeometry(); geometry.setIndex( new BufferAttribute( indices, 1 ) ); geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) ); LineSegments.call( this, geometry, new LineBasicMaterial( { color: color } ) ); this.matrixAutoUpdate = false; this.update(); } BoxHelper.prototype = Object.create( LineSegments.prototype ); BoxHelper.prototype.constructor = BoxHelper; BoxHelper.prototype.update = function ( object ) { if ( object !== undefined ) { console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' ); } if ( this.object !== undefined ) { _box$3.setFromObject( this.object ); } if ( _box$3.isEmpty() ) { return; } var min = _box$3.min; var max = _box$3.max; /* 5____4 1/___0/| | 6__|_7 2/___3/ 0: max.x, max.y, max.z 1: min.x, max.y, max.z 2: min.x, min.y, max.z 3: max.x, min.y, max.z 4: max.x, max.y, min.z 5: min.x, max.y, min.z 6: min.x, min.y, min.z 7: max.x, min.y, min.z */ var position = this.geometry.attributes.position; var array = position.array; array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z; array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z; array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z; array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z; array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z; array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z; array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z; array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z; position.needsUpdate = true; this.geometry.computeBoundingSphere(); }; BoxHelper.prototype.setFromObject = function ( object ) { this.object = object; this.update(); return this; }; BoxHelper.prototype.copy = function ( source ) { LineSegments.prototype.copy.call( this, source ); this.object = source.object; return this; }; BoxHelper.prototype.clone = function () { return new this.constructor().copy( this ); }; /** * @author WestLangley / http://github.com/WestLangley */ function Box3Helper( box, color ) { this.type = 'Box3Helper'; this.box = box; color = color || 0xffff00; var indices = new Uint16Array( [ 0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7 ] ); var positions = [ 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, - 1, 1, 1, 1, - 1, - 1, 1, - 1, - 1, - 1, - 1, 1, - 1, - 1 ]; var geometry = new BufferGeometry(); geometry.setIndex( new BufferAttribute( indices, 1 ) ); geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) ); LineSegments.call( this, geometry, new LineBasicMaterial( { color: color } ) ); this.geometry.computeBoundingSphere(); } Box3Helper.prototype = Object.create( LineSegments.prototype ); Box3Helper.prototype.constructor = Box3Helper; Box3Helper.prototype.updateMatrixWorld = function ( force ) { var box = this.box; if ( box.isEmpty() ) { return; } box.getCenter( this.position ); box.getSize( this.scale ); this.scale.multiplyScalar( 0.5 ); Object3D.prototype.updateMatrixWorld.call( this, force ); }; /** * @author WestLangley / http://github.com/WestLangley */ function PlaneHelper( plane, size, hex ) { this.type = 'PlaneHelper'; this.plane = plane; this.size = ( size === undefined ) ? 1 : size; var color = ( hex !== undefined ) ? hex : 0xffff00; var positions = [ 1, - 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, - 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0 ]; var geometry = new BufferGeometry(); geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) ); geometry.computeBoundingSphere(); Line.call( this, geometry, new LineBasicMaterial( { color: color } ) ); // var positions2 = [ 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, 1, 1, - 1, - 1, 1, 1, - 1, 1 ]; var geometry2 = new BufferGeometry(); geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) ); geometry2.computeBoundingSphere(); this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false } ) ) ); } PlaneHelper.prototype = Object.create( Line.prototype ); PlaneHelper.prototype.constructor = PlaneHelper; PlaneHelper.prototype.updateMatrixWorld = function ( force ) { var scale = - this.plane.constant; if ( Math.abs( scale ) < 1e-8 ) { scale = 1e-8; } // sign does not matter this.scale.set( 0.5 * this.size, 0.5 * this.size, scale ); this.children[ 0 ].material.side = ( scale < 0 ) ? BackSide : FrontSide; // renderer flips side when determinant < 0; flipping not wanted here this.lookAt( this.plane.normal ); Object3D.prototype.updateMatrixWorld.call( this, force ); }; /** * @author WestLangley / http://github.com/WestLangley * @author zz85 / http://github.com/zz85 * @author bhouston / http://clara.io * * Creates an arrow for visualizing directions * * Parameters: * dir - Vector3 * origin - Vector3 * length - Number * color - color in hex value * headLength - Number * headWidth - Number */ var _axis = new Vector3(); var _lineGeometry, _coneGeometry; function ArrowHelper( dir, origin, length, color, headLength, headWidth ) { // dir is assumed to be normalized Object3D.call( this ); if ( dir === undefined ) { dir = new Vector3( 0, 0, 1 ); } if ( origin === undefined ) { origin = new Vector3( 0, 0, 0 ); } if ( length === undefined ) { length = 1; } if ( color === undefined ) { color = 0xffff00; } if ( headLength === undefined ) { headLength = 0.2 * length; } if ( headWidth === undefined ) { headWidth = 0.2 * headLength; } if ( _lineGeometry === undefined ) { _lineGeometry = new BufferGeometry(); _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) ); _coneGeometry = new CylinderBufferGeometry( 0, 0.5, 1, 5, 1 ); _coneGeometry.translate( 0, - 0.5, 0 ); } this.position.copy( origin ); this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color } ) ); this.line.matrixAutoUpdate = false; this.add( this.line ); this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color } ) ); this.cone.matrixAutoUpdate = false; this.add( this.cone ); this.setDirection( dir ); this.setLength( length, headLength, headWidth ); } ArrowHelper.prototype = Object.create( Object3D.prototype ); ArrowHelper.prototype.constructor = ArrowHelper; ArrowHelper.prototype.setDirection = function ( dir ) { // dir is assumed to be normalized if ( dir.y > 0.99999 ) { this.quaternion.set( 0, 0, 0, 1 ); } else if ( dir.y < - 0.99999 ) { this.quaternion.set( 1, 0, 0, 0 ); } else { _axis.set( dir.z, 0, - dir.x ).normalize(); var radians = Math.acos( dir.y ); this.quaternion.setFromAxisAngle( _axis, radians ); } }; ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) { if ( headLength === undefined ) { headLength = 0.2 * length; } if ( headWidth === undefined ) { headWidth = 0.2 * headLength; } this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458 this.line.updateMatrix(); this.cone.scale.set( headWidth, headLength, headWidth ); this.cone.position.y = length; this.cone.updateMatrix(); }; ArrowHelper.prototype.setColor = function ( color ) { this.line.material.color.set( color ); this.cone.material.color.set( color ); }; ArrowHelper.prototype.copy = function ( source ) { Object3D.prototype.copy.call( this, source, false ); this.line.copy( source.line ); this.cone.copy( source.cone ); return this; }; ArrowHelper.prototype.clone = function () { return new this.constructor().copy( this ); }; /** * @author sroucheray / http://sroucheray.org/ * @author mrdoob / http://mrdoob.com/ */ function AxesHelper( size ) { size = size || 1; var vertices = [ 0, 0, 0, size, 0, 0, 0, 0, 0, 0, size, 0, 0, 0, 0, 0, 0, size ]; var colors = [ 1, 0, 0, 1, 0.6, 0, 0, 1, 0, 0.6, 1, 0, 0, 0, 1, 0, 0.6, 1 ]; var geometry = new BufferGeometry(); geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) ); geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) ); var material = new LineBasicMaterial( { vertexColors: VertexColors } ); LineSegments.call( this, geometry, material ); } AxesHelper.prototype = Object.create( LineSegments.prototype ); AxesHelper.prototype.constructor = AxesHelper; /** * @author Emmett Lalish / elalish * * This class generates a Prefiltered, Mipmapped Radiance Environment Map * (PMREM) from a cubeMap environment texture. This allows different levels of * blur to be quickly accessed based on material roughness. It is packed into a * special CubeUV format that allows us to perform custom interpolation so that * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap * chain, it only goes down to the LOD_MIN level (above), and then creates extra * even more filtered 'mips' at the same LOD_MIN resolution, associated with * higher roughness levels. In this way we maintain resolution to smoothly * interpolate diffuse lighting while limiting sampling computation. */ var LOD_MIN = 4; var LOD_MAX = 8; var SIZE_MAX = Math.pow( 2, LOD_MAX ); // The standard deviations (radians) associated with the extra mips. These are // chosen to approximate a Trowbridge-Reitz distribution function times the // geometric shadowing function. These sigma values squared must match the // variance #defines in cube_uv_reflection_fragment.glsl.js. var EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ]; var TOTAL_LODS = LOD_MAX - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length; // The maximum length of the blur for loop. Smaller sigmas will use fewer // samples and exit early, but not recompile the shader. var MAX_SAMPLES = 20; var ENCODINGS = {}; ENCODINGS[ LinearEncoding ] = 0; ENCODINGS[ sRGBEncoding ] = 1; ENCODINGS[ RGBEEncoding ] = 2; ENCODINGS[ RGBM7Encoding ] = 3; ENCODINGS[ RGBM16Encoding ] = 4; ENCODINGS[ RGBDEncoding ] = 5; ENCODINGS[ GammaEncoding ] = 6; var _flatCamera = new OrthographicCamera(); var _blurMaterial = _getBlurShader( MAX_SAMPLES ); var _equirectShader = null; var _cubemapShader = null; var ref = _createPlanes(); var _lodPlanes = ref._lodPlanes; var _sizeLods = ref._sizeLods; var _sigmas = ref._sigmas; var _pingPongRenderTarget = null; var _renderer = null; var _oldTarget = null; // Golden Ratio var PHI = ( 1 + Math.sqrt( 5 ) ) / 2; var INV_PHI = 1 / PHI; // Vertices of a dodecahedron (except the opposites, which represent the // same axis), used as axis directions evenly spread on a sphere. var _axisDirections = [ new Vector3( 1, 1, 1 ), new Vector3( - 1, 1, 1 ), new Vector3( 1, 1, - 1 ), new Vector3( - 1, 1, - 1 ), new Vector3( 0, PHI, INV_PHI ), new Vector3( 0, PHI, - INV_PHI ), new Vector3( INV_PHI, 0, PHI ), new Vector3( - INV_PHI, 0, PHI ), new Vector3( PHI, INV_PHI, 0 ), new Vector3( - PHI, INV_PHI, 0 ) ]; function PMREMGenerator( renderer ) { _renderer = renderer; _compileMaterial( _blurMaterial ); } PMREMGenerator.prototype = { constructor: PMREMGenerator, /** * Generates a PMREM from a supplied Scene, which can be faster than using an * image if networking bandwidth is low. Optional sigma specifies a blur radius * in radians to be applied to the scene before PMREM generation. Optional near * and far planes ensure the scene is rendered in its entirety (the cubeCamera * is placed at the origin). */ fromScene: function ( scene, sigma, near, far ) { if ( sigma === void 0 ) sigma = 0; if ( near === void 0 ) near = 0.1; if ( far === void 0 ) far = 100; _oldTarget = _renderer.getRenderTarget(); var cubeUVRenderTarget = _allocateTargets(); _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ); if ( sigma > 0 ) { _blur( cubeUVRenderTarget, 0, 0, sigma ); } _applyPMREM( cubeUVRenderTarget ); _cleanup( cubeUVRenderTarget ); return cubeUVRenderTarget; }, /** * Generates a PMREM from an equirectangular texture, which can be either LDR * (RGBFormat) or HDR (RGBEFormat). The ideal input image size is 1k (1024 x 512), * as this matches best with the 256 x 256 cubemap output. */ fromEquirectangular: function ( equirectangular ) { equirectangular.magFilter = NearestFilter; equirectangular.minFilter = NearestFilter; equirectangular.generateMipmaps = false; return this.fromCubemap( equirectangular ); }, /** * Generates a PMREM from an cubemap texture, which can be either LDR * (RGBFormat) or HDR (RGBEFormat). The ideal input cube size is 256 x 256, * as this matches best with the 256 x 256 cubemap output. */ fromCubemap: function ( cubemap ) { _oldTarget = _renderer.getRenderTarget(); var cubeUVRenderTarget = _allocateTargets( cubemap ); _textureToCubeUV( cubemap, cubeUVRenderTarget ); _applyPMREM( cubeUVRenderTarget ); _cleanup( cubeUVRenderTarget ); return cubeUVRenderTarget; }, /** * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during * your texture's network fetch for increased concurrency. */ compileCubemapShader: function () { if ( _cubemapShader == null ) { _cubemapShader = _getCubemapShader(); _compileMaterial( _cubemapShader ); } }, /** * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during * your texture's network fetch for increased concurrency. */ compileEquirectangularShader: function () { if ( _equirectShader == null ) { _equirectShader = _getEquirectShader(); _compileMaterial( _equirectShader ); } }, /** * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class, * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on * one of them will cause any others to also become unusable. */ dispose: function () { _blurMaterial.dispose(); if ( _cubemapShader != null ) { _cubemapShader.dispose(); } if ( _equirectShader != null ) { _equirectShader.dispose(); } for ( var i = 0; i < _lodPlanes.length; i ++ ) { _lodPlanes[ i ].dispose(); } }, }; function _createPlanes() { var _lodPlanes = []; var _sizeLods = []; var _sigmas = []; var lod = LOD_MAX; for ( var i = 0; i < TOTAL_LODS; i ++ ) { var sizeLod = Math.pow( 2, lod ); _sizeLods.push( sizeLod ); var sigma = 1.0 / sizeLod; if ( i > LOD_MAX - LOD_MIN ) { sigma = EXTRA_LOD_SIGMA[ i - LOD_MAX + LOD_MIN - 1 ]; } else if ( i == 0 ) { sigma = 0; } _sigmas.push( sigma ); var texelSize = 1.0 / ( sizeLod - 1 ); var min = - texelSize / 2; var max = 1 + texelSize / 2; var uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ]; var cubeFaces = 6; var vertices = 6; var positionSize = 3; var uvSize = 2; var faceIndexSize = 1; var position = new Float32Array( positionSize * vertices * cubeFaces ); var uv = new Float32Array( uvSize * vertices * cubeFaces ); var faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces ); for ( var face = 0; face < cubeFaces; face ++ ) { var x = ( face % 3 ) * 2 / 3 - 1; var y = face > 2 ? 0 : - 1; var coordinates = [ x, y, 0, x + 2 / 3, y, 0, x + 2 / 3, y + 1, 0, x, y, 0, x + 2 / 3, y + 1, 0, x, y + 1, 0 ]; position.set( coordinates, positionSize * vertices * face ); uv.set( uv1, uvSize * vertices * face ); var fill = [ face, face, face, face, face, face ]; faceIndex.set( fill, faceIndexSize * vertices * face ); } var planes = new BufferGeometry(); planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) ); planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) ); planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) ); _lodPlanes.push( planes ); if ( lod > LOD_MIN ) { lod --; } } return { _lodPlanes: _lodPlanes, _sizeLods: _sizeLods, _sigmas: _sigmas }; } function _allocateTargets( equirectangular ) { var params = { magFilter: NearestFilter, minFilter: NearestFilter, generateMipmaps: false, type: equirectangular ? equirectangular.type : UnsignedByteType, format: equirectangular ? equirectangular.format : RGBEFormat, encoding: equirectangular ? equirectangular.encoding : RGBEEncoding, depthBuffer: false, stencilBuffer: false }; var cubeUVRenderTarget = _createRenderTarget( params ); cubeUVRenderTarget.depthBuffer = equirectangular ? false : true; _pingPongRenderTarget = _createRenderTarget( params ); return cubeUVRenderTarget; } function _cleanup( outputTarget ) { _pingPongRenderTarget.dispose(); _renderer.setRenderTarget( _oldTarget ); outputTarget.scissorTest = false; // reset viewport and scissor outputTarget.setSize( outputTarget.width, outputTarget.height ); } function _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) { var fov = 90; var aspect = 1; var cubeCamera = new PerspectiveCamera( fov, aspect, near, far ); var upSign = [ 1, 1, 1, 1, - 1, 1 ]; var forwardSign = [ 1, 1, - 1, - 1, - 1, 1 ]; var outputEncoding = _renderer.outputEncoding; var toneMapping = _renderer.toneMapping; var toneMappingExposure = _renderer.toneMappingExposure; var clearColor = _renderer.getClearColor(); var clearAlpha = _renderer.getClearAlpha(); _renderer.toneMapping = LinearToneMapping; _renderer.toneMappingExposure = 1.0; _renderer.outputEncoding = LinearEncoding; scene.scale.z *= - 1; var background = scene.background; if ( background && background.isColor ) { background.convertSRGBToLinear(); // Convert linear to RGBE var maxComponent = Math.max( background.r, background.g, background.b ); var fExp = Math.min( Math.max( Math.ceil( Math.log2( maxComponent ) ), - 128.0 ), 127.0 ); background = background.multiplyScalar( Math.pow( 2.0, - fExp ) ); var alpha = ( fExp + 128.0 ) / 255.0; _renderer.setClearColor( background, alpha ); scene.background = null; } for ( var i = 0; i < 6; i ++ ) { var col = i % 3; if ( col == 0 ) { cubeCamera.up.set( 0, upSign[ i ], 0 ); cubeCamera.lookAt( forwardSign[ i ], 0, 0 ); } else if ( col == 1 ) { cubeCamera.up.set( 0, 0, upSign[ i ] ); cubeCamera.lookAt( 0, forwardSign[ i ], 0 ); } else { cubeCamera.up.set( 0, upSign[ i ], 0 ); cubeCamera.lookAt( 0, 0, forwardSign[ i ] ); } _setViewport( cubeUVRenderTarget, col * SIZE_MAX, i > 2 ? SIZE_MAX : 0, SIZE_MAX, SIZE_MAX ); _renderer.setRenderTarget( cubeUVRenderTarget ); _renderer.render( scene, cubeCamera ); } _renderer.toneMapping = toneMapping; _renderer.toneMappingExposure = toneMappingExposure; _renderer.outputEncoding = outputEncoding; _renderer.setClearColor( clearColor, clearAlpha ); scene.scale.z *= - 1; } function _textureToCubeUV( texture, cubeUVRenderTarget ) { var scene = new Scene(); if ( texture.isCubeTexture ) { if ( _cubemapShader == null ) { _cubemapShader = _getCubemapShader(); } } else { if ( _equirectShader == null ) { _equirectShader = _getEquirectShader(); } } var material = texture.isCubeTexture ? _cubemapShader : _equirectShader; scene.add( new Mesh( _lodPlanes[ 0 ], material ) ); var uniforms = material.uniforms; uniforms[ 'envMap' ].value = texture; if ( ! texture.isCubeTexture ) { uniforms[ 'texelSize' ].value.set( 1.0 / texture.image.width, 1.0 / texture.image.height ); } uniforms[ 'inputEncoding' ].value = ENCODINGS[ texture.encoding ]; uniforms[ 'outputEncoding' ].value = ENCODINGS[ texture.encoding ]; _setViewport( cubeUVRenderTarget, 0, 0, 3 * SIZE_MAX, 2 * SIZE_MAX ); _renderer.setRenderTarget( cubeUVRenderTarget ); _renderer.render( scene, _flatCamera ); } function _compileMaterial( material ) { var tmpScene = new Scene(); tmpScene.add( new Mesh( _lodPlanes[ 0 ], material ) ); _renderer.compile( tmpScene, _flatCamera ); } function _createRenderTarget( params ) { var cubeUVRenderTarget = new WebGLRenderTarget( 3 * SIZE_MAX, 3 * SIZE_MAX, params ); cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping; cubeUVRenderTarget.texture.name = 'PMREM.cubeUv'; cubeUVRenderTarget.scissorTest = true; return cubeUVRenderTarget; } function _setViewport( target, x, y, width, height ) { target.viewport.set( x, y, width, height ); target.scissor.set( x, y, width, height ); } function _applyPMREM( cubeUVRenderTarget ) { var autoClear = _renderer.autoClear; _renderer.autoClear = false; for ( var i = 1; i < TOTAL_LODS; i ++ ) { var sigma = Math.sqrt( _sigmas[ i ] * _sigmas[ i ] - _sigmas[ i - 1 ] * _sigmas[ i - 1 ] ); var poleAxis = _axisDirections[ ( i - 1 ) % _axisDirections.length ]; _blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis ); } _renderer.autoClear = autoClear; } /** * This is a two-pass Gaussian blur for a cubemap. Normally this is done * vertically and horizontally, but this breaks down on a cube. Here we apply * the blur latitudinally (around the poles), and then longitudinally (towards * the poles) to approximate the orthogonally-separable blur. It is least * accurate at the poles, but still does a decent job. */ function _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) { _halfBlur( cubeUVRenderTarget, _pingPongRenderTarget, lodIn, lodOut, sigma, 'latitudinal', poleAxis ); _halfBlur( _pingPongRenderTarget, cubeUVRenderTarget, lodOut, lodOut, sigma, 'longitudinal', poleAxis ); } function _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) { if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) { console.error( 'blur direction must be either latitudinal or longitudinal!' ); } // Number of standard deviations at which to cut off the discrete approximation. var STANDARD_DEVIATIONS = 3; var blurScene = new Scene(); blurScene.add( new Mesh( _lodPlanes[ lodOut ], _blurMaterial ) ); var blurUniforms = _blurMaterial.uniforms; var pixels = _sizeLods[ lodIn ] - 1; var radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 ); var sigmaPixels = sigmaRadians / radiansPerPixel; var samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES; if ( samples > MAX_SAMPLES ) { console.warn( ("sigmaRadians, " + sigmaRadians + ", is too large and will clip, as it requested " + samples + " samples when the maximum is set to " + MAX_SAMPLES) ); } var weights = []; var sum = 0; for ( var i = 0; i < MAX_SAMPLES; ++ i ) { var x = i / sigmaPixels; var weight = Math.exp( - x * x / 2 ); weights.push( weight ); if ( i == 0 ) { sum += weight; } else if ( i < samples ) { sum += 2 * weight; } } for ( var i = 0; i < weights.length; i ++ ) { weights[ i ] = weights[ i ] / sum; } blurUniforms[ 'envMap' ].value = targetIn.texture; blurUniforms[ 'samples' ].value = samples; blurUniforms[ 'weights' ].value = weights; blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal'; if ( poleAxis ) { blurUniforms[ 'poleAxis' ].value = poleAxis; } blurUniforms[ 'dTheta' ].value = radiansPerPixel; blurUniforms[ 'mipInt' ].value = LOD_MAX - lodIn; blurUniforms[ 'inputEncoding' ].value = ENCODINGS[ targetIn.texture.encoding ]; blurUniforms[ 'outputEncoding' ].value = ENCODINGS[ targetIn.texture.encoding ]; var outputSize = _sizeLods[ lodOut ]; var x = 3 * Math.max( 0, SIZE_MAX - 2 * outputSize ); var y = ( lodOut === 0 ? 0 : 2 * SIZE_MAX ) + 2 * outputSize * ( lodOut > LOD_MAX - LOD_MIN ? lodOut - LOD_MAX + LOD_MIN : 0 ); _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize ); _renderer.setRenderTarget( targetOut ); _renderer.render( blurScene, _flatCamera ); } function _getBlurShader( maxSamples ) { var weights = new Float32Array( maxSamples ); var poleAxis = new Vector3( 0, 1, 0 ); var shaderMaterial = new RawShaderMaterial( { defines: { 'n': maxSamples }, uniforms: { 'envMap': { value: null }, 'samples': { value: 1 }, 'weights': { value: weights }, 'latitudinal': { value: false }, 'dTheta': { value: 0 }, 'mipInt': { value: 0 }, 'poleAxis': { value: poleAxis }, 'inputEncoding': { value: ENCODINGS[ LinearEncoding ] }, 'outputEncoding': { value: ENCODINGS[ LinearEncoding ] } }, vertexShader: _getCommonVertexShader(), fragmentShader: ("\nprecision mediump float;\nprecision mediump int;\nvarying vec3 vOutputDirection;\nuniform sampler2D envMap;\nuniform int samples;\nuniform float weights[n];\nuniform bool latitudinal;\nuniform float dTheta;\nuniform float mipInt;\nuniform vec3 poleAxis;\n\n" + (_getEncodings()) + "\n\n#define ENVMAP_TYPE_CUBE_UV\n#include \n\nvoid main() {\n\tgl_FragColor = vec4(0.0);\n\tfor (int i = 0; i < n; i++) {\n\t\tif (i >= samples)\n\t\t\tbreak;\n\t\tfor (int dir = -1; dir < 2; dir += 2) {\n\t\t\tif (i == 0 && dir == 1)\n\t\t\t\tcontinue;\n\t\t\tvec3 axis = latitudinal ? poleAxis : cross(poleAxis, vOutputDirection);\n\t\t\tif (all(equal(axis, vec3(0.0))))\n\t\t\t\taxis = cross(vec3(0.0, 1.0, 0.0), vOutputDirection);\n\t\t\taxis = normalize(axis);\n\t\t\tfloat theta = dTheta * float(dir * i);\n\t\t\tfloat cosTheta = cos(theta);\n\t\t\t// Rodrigues' axis-angle rotation\n\t\t\tvec3 sampleDirection = vOutputDirection * cosTheta\n\t\t\t\t\t+ cross(axis, vOutputDirection) * sin(theta)\n\t\t\t\t\t+ axis * dot(axis, vOutputDirection) * (1.0 - cosTheta);\n\t\t\tgl_FragColor.rgb +=\n\t\t\t\t\tweights[i] * bilinearCubeUV(envMap, sampleDirection, mipInt);\n\t\t}\n\t}\n\tgl_FragColor = linearToOutputTexel(gl_FragColor);\n}\n\t\t"), blending: NoBlending, depthTest: false, depthWrite: false } ); shaderMaterial.type = 'SphericalGaussianBlur'; return shaderMaterial; } function _getEquirectShader() { var texelSize = new Vector2( 1, 1 ); var shaderMaterial = new RawShaderMaterial( { uniforms: { 'envMap': { value: null }, 'texelSize': { value: texelSize }, 'inputEncoding': { value: ENCODINGS[ LinearEncoding ] }, 'outputEncoding': { value: ENCODINGS[ LinearEncoding ] } }, vertexShader: _getCommonVertexShader(), fragmentShader: ("\nprecision mediump float;\nprecision mediump int;\nvarying vec3 vOutputDirection;\nuniform sampler2D envMap;\nuniform vec2 texelSize;\n\n" + (_getEncodings()) + "\n\n#define RECIPROCAL_PI 0.31830988618\n#define RECIPROCAL_PI2 0.15915494\n\nvoid main() {\n\tgl_FragColor = vec4(0.0);\n\tvec3 outputDirection = normalize(vOutputDirection);\n\tvec2 uv;\n\tuv.y = asin(clamp(outputDirection.y, -1.0, 1.0)) * RECIPROCAL_PI + 0.5;\n\tuv.x = atan(outputDirection.z, outputDirection.x) * RECIPROCAL_PI2 + 0.5;\n\tvec2 f = fract(uv / texelSize - 0.5);\n\tuv -= f * texelSize;\n\tvec3 tl = envMapTexelToLinear(texture2D(envMap, uv)).rgb;\n\tuv.x += texelSize.x;\n\tvec3 tr = envMapTexelToLinear(texture2D(envMap, uv)).rgb;\n\tuv.y += texelSize.y;\n\tvec3 br = envMapTexelToLinear(texture2D(envMap, uv)).rgb;\n\tuv.x -= texelSize.x;\n\tvec3 bl = envMapTexelToLinear(texture2D(envMap, uv)).rgb;\n\tvec3 tm = mix(tl, tr, f.x);\n\tvec3 bm = mix(bl, br, f.x);\n\tgl_FragColor.rgb = mix(tm, bm, f.y);\n\tgl_FragColor = linearToOutputTexel(gl_FragColor);\n}\n\t\t"), blending: NoBlending, depthTest: false, depthWrite: false } ); shaderMaterial.type = 'EquirectangularToCubeUV'; return shaderMaterial; } function _getCubemapShader() { var shaderMaterial = new RawShaderMaterial( { uniforms: { 'envMap': { value: null }, 'inputEncoding': { value: ENCODINGS[ LinearEncoding ] }, 'outputEncoding': { value: ENCODINGS[ LinearEncoding ] } }, vertexShader: _getCommonVertexShader(), fragmentShader: ("\nprecision mediump float;\nprecision mediump int;\nvarying vec3 vOutputDirection;\nuniform samplerCube envMap;\n\n" + (_getEncodings()) + "\n\nvoid main() {\n\tgl_FragColor = vec4(0.0);\n\tgl_FragColor.rgb = envMapTexelToLinear(textureCube(envMap, vec3( - vOutputDirection.x, vOutputDirection.yz ))).rgb;\n\tgl_FragColor = linearToOutputTexel(gl_FragColor);\n}\n\t\t"), blending: NoBlending, depthTest: false, depthWrite: false } ); shaderMaterial.type = 'CubemapToCubeUV'; return shaderMaterial; } function _getCommonVertexShader() { return "\nprecision mediump float;\nprecision mediump int;\nattribute vec3 position;\nattribute vec2 uv;\nattribute float faceIndex;\nvarying vec3 vOutputDirection;\nvec3 getDirection(vec2 uv, float face) {\n\tuv = 2.0 * uv - 1.0;\n\tvec3 direction = vec3(uv, 1.0);\n\tif (face == 0.0) {\n\t\tdirection = direction.zyx;\n\t\tdirection.z *= -1.0;\n\t} else if (face == 1.0) {\n\t\tdirection = direction.xzy;\n\t\tdirection.z *= -1.0;\n\t} else if (face == 3.0) {\n\t\tdirection = direction.zyx;\n\t\tdirection.x *= -1.0;\n\t} else if (face == 4.0) {\n\t\tdirection = direction.xzy;\n\t\tdirection.y *= -1.0;\n\t} else if (face == 5.0) {\n\t\tdirection.xz *= -1.0;\n\t}\n\treturn direction;\n}\nvoid main() {\n\tvOutputDirection = getDirection(uv, faceIndex);\n\tgl_Position = vec4( position, 1.0 );\n}\n\t"; } function _getEncodings() { return "\nuniform int inputEncoding;\nuniform int outputEncoding;\n\n#include \n\nvec4 inputTexelToLinear(vec4 value){\n\tif(inputEncoding == 0){\n\t\treturn value;\n\t}else if(inputEncoding == 1){\n\t\treturn sRGBToLinear(value);\n\t}else if(inputEncoding == 2){\n\t\treturn RGBEToLinear(value);\n\t}else if(inputEncoding == 3){\n\t\treturn RGBMToLinear(value, 7.0);\n\t}else if(inputEncoding == 4){\n\t\treturn RGBMToLinear(value, 16.0);\n\t}else if(inputEncoding == 5){\n\t\treturn RGBDToLinear(value, 256.0);\n\t}else{\n\t\treturn GammaToLinear(value, 2.2);\n\t}\n}\n\nvec4 linearToOutputTexel(vec4 value){\n\tif(outputEncoding == 0){\n\t\treturn value;\n\t}else if(outputEncoding == 1){\n\t\treturn LinearTosRGB(value);\n\t}else if(outputEncoding == 2){\n\t\treturn LinearToRGBE(value);\n\t}else if(outputEncoding == 3){\n\t\treturn LinearToRGBM(value, 7.0);\n\t}else if(outputEncoding == 4){\n\t\treturn LinearToRGBM(value, 16.0);\n\t}else if(outputEncoding == 5){\n\t\treturn LinearToRGBD(value, 256.0);\n\t}else{\n\t\treturn LinearToGamma(value, 2.2);\n\t}\n}\n\nvec4 envMapTexelToLinear(vec4 color) {\n\treturn inputTexelToLinear(color);\n}\n\t"; } /** * @author mrdoob / http://mrdoob.com/ */ function Face4( a, b, c, d, normal, color, materialIndex ) { console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.' ); return new Face3( a, b, c, normal, color, materialIndex ); } var LineStrip = 0; var LinePieces = 1; function MeshFaceMaterial( materials ) { console.warn( 'THREE.MeshFaceMaterial has been removed. Use an Array instead.' ); return materials; } function MultiMaterial( materials ) { if ( materials === undefined ) { materials = []; } console.warn( 'THREE.MultiMaterial has been removed. Use an Array instead.' ); materials.isMultiMaterial = true; materials.materials = materials; materials.clone = function () { return materials.slice(); }; return materials; } function PointCloud( geometry, material ) { console.warn( 'THREE.PointCloud has been renamed to THREE.Points.' ); return new Points( geometry, material ); } function Particle( material ) { console.warn( 'THREE.Particle has been renamed to THREE.Sprite.' ); return new Sprite( material ); } function ParticleSystem( geometry, material ) { console.warn( 'THREE.ParticleSystem has been renamed to THREE.Points.' ); return new Points( geometry, material ); } function PointCloudMaterial( parameters ) { console.warn( 'THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.' ); return new PointsMaterial( parameters ); } function ParticleBasicMaterial( parameters ) { console.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.' ); return new PointsMaterial( parameters ); } function ParticleSystemMaterial( parameters ) { console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.' ); return new PointsMaterial( parameters ); } function Vertex( x, y, z ) { console.warn( 'THREE.Vertex has been removed. Use THREE.Vector3 instead.' ); return new Vector3( x, y, z ); } // function DynamicBufferAttribute( array, itemSize ) { console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setUsage( THREE.DynamicDrawUsage ) instead.' ); return new BufferAttribute( array, itemSize ).setUsage( DynamicDrawUsage ); } function Int8Attribute( array, itemSize ) { console.warn( 'THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.' ); return new Int8BufferAttribute( array, itemSize ); } function Uint8Attribute( array, itemSize ) { console.warn( 'THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.' ); return new Uint8BufferAttribute( array, itemSize ); } function Uint8ClampedAttribute( array, itemSize ) { console.warn( 'THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.' ); return new Uint8ClampedBufferAttribute( array, itemSize ); } function Int16Attribute( array, itemSize ) { console.warn( 'THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.' ); return new Int16BufferAttribute( array, itemSize ); } function Uint16Attribute( array, itemSize ) { console.warn( 'THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.' ); return new Uint16BufferAttribute( array, itemSize ); } function Int32Attribute( array, itemSize ) { console.warn( 'THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.' ); return new Int32BufferAttribute( array, itemSize ); } function Uint32Attribute( array, itemSize ) { console.warn( 'THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.' ); return new Uint32BufferAttribute( array, itemSize ); } function Float32Attribute( array, itemSize ) { console.warn( 'THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.' ); return new Float32BufferAttribute( array, itemSize ); } function Float64Attribute( array, itemSize ) { console.warn( 'THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.' ); return new Float64BufferAttribute( array, itemSize ); } // Curve.create = function ( construct, getPoint ) { console.log( 'THREE.Curve.create() has been deprecated' ); construct.prototype = Object.create( Curve.prototype ); construct.prototype.constructor = construct; construct.prototype.getPoint = getPoint; return construct; }; // Object.assign( CurvePath.prototype, { createPointsGeometry: function ( divisions ) { console.warn( 'THREE.CurvePath: .createPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.' ); // generate geometry from path points (for Line or Points objects) var pts = this.getPoints( divisions ); return this.createGeometry( pts ); }, createSpacedPointsGeometry: function ( divisions ) { console.warn( 'THREE.CurvePath: .createSpacedPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.' ); // generate geometry from equidistant sampling along the path var pts = this.getSpacedPoints( divisions ); return this.createGeometry( pts ); }, createGeometry: function ( points ) { console.warn( 'THREE.CurvePath: .createGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.' ); var geometry = new Geometry(); for ( var i = 0, l = points.length; i < l; i ++ ) { var point = points[ i ]; geometry.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) ); } return geometry; } } ); // Object.assign( Path.prototype, { fromPoints: function ( points ) { console.warn( 'THREE.Path: .fromPoints() has been renamed to .setFromPoints().' ); return this.setFromPoints( points ); } } ); // function ClosedSplineCurve3( points ) { console.warn( 'THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' ); CatmullRomCurve3.call( this, points ); this.type = 'catmullrom'; this.closed = true; } ClosedSplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype ); // function SplineCurve3( points ) { console.warn( 'THREE.SplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' ); CatmullRomCurve3.call( this, points ); this.type = 'catmullrom'; } SplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype ); // function Spline( points ) { console.warn( 'THREE.Spline has been removed. Use THREE.CatmullRomCurve3 instead.' ); CatmullRomCurve3.call( this, points ); this.type = 'catmullrom'; } Spline.prototype = Object.create( CatmullRomCurve3.prototype ); Object.assign( Spline.prototype, { initFromArray: function ( /* a */ ) { console.error( 'THREE.Spline: .initFromArray() has been removed.' ); }, getControlPointsArray: function ( /* optionalTarget */ ) { console.error( 'THREE.Spline: .getControlPointsArray() has been removed.' ); }, reparametrizeByArcLength: function ( /* samplingCoef */ ) { console.error( 'THREE.Spline: .reparametrizeByArcLength() has been removed.' ); } } ); // function AxisHelper( size ) { console.warn( 'THREE.AxisHelper has been renamed to THREE.AxesHelper.' ); return new AxesHelper( size ); } function BoundingBoxHelper( object, color ) { console.warn( 'THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.' ); return new BoxHelper( object, color ); } function EdgesHelper( object, hex ) { console.warn( 'THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.' ); return new LineSegments( new EdgesGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) ); } GridHelper.prototype.setColors = function () { console.error( 'THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.' ); }; SkeletonHelper.prototype.update = function () { console.error( 'THREE.SkeletonHelper: update() no longer needs to be called.' ); }; function WireframeHelper( object, hex ) { console.warn( 'THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.' ); return new LineSegments( new WireframeGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) ); } // Object.assign( Loader.prototype, { extractUrlBase: function ( url ) { console.warn( 'THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.' ); return LoaderUtils.extractUrlBase( url ); } } ); Loader.Handlers = { add: function ( /* regex, loader */ ) { console.error( 'THREE.Loader: Handlers.add() has been removed. Use LoadingManager.addHandler() instead.' ); }, get: function ( /* file */ ) { console.error( 'THREE.Loader: Handlers.get() has been removed. Use LoadingManager.getHandler() instead.' ); } }; function XHRLoader( manager ) { console.warn( 'THREE.XHRLoader has been renamed to THREE.FileLoader.' ); return new FileLoader( manager ); } function BinaryTextureLoader( manager ) { console.warn( 'THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.' ); return new DataTextureLoader( manager ); } Object.assign( ObjectLoader.prototype, { setTexturePath: function ( value ) { console.warn( 'THREE.ObjectLoader: .setTexturePath() has been renamed to .setResourcePath().' ); return this.setResourcePath( value ); } } ); // Object.assign( Box2.prototype, { center: function ( optionalTarget ) { console.warn( 'THREE.Box2: .center() has been renamed to .getCenter().' ); return this.getCenter( optionalTarget ); }, empty: function () { console.warn( 'THREE.Box2: .empty() has been renamed to .isEmpty().' ); return this.isEmpty(); }, isIntersectionBox: function ( box ) { console.warn( 'THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().' ); return this.intersectsBox( box ); }, size: function ( optionalTarget ) { console.warn( 'THREE.Box2: .size() has been renamed to .getSize().' ); return this.getSize( optionalTarget ); } } ); Object.assign( Box3.prototype, { center: function ( optionalTarget ) { console.warn( 'THREE.Box3: .center() has been renamed to .getCenter().' ); return this.getCenter( optionalTarget ); }, empty: function () { console.warn( 'THREE.Box3: .empty() has been renamed to .isEmpty().' ); return this.isEmpty(); }, isIntersectionBox: function ( box ) { console.warn( 'THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().' ); return this.intersectsBox( box ); }, isIntersectionSphere: function ( sphere ) { console.warn( 'THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().' ); return this.intersectsSphere( sphere ); }, size: function ( optionalTarget ) { console.warn( 'THREE.Box3: .size() has been renamed to .getSize().' ); return this.getSize( optionalTarget ); } } ); Frustum.prototype.setFromMatrix = function ( m ) { console.warn( 'THREE.Frustum: .setFromMatrix() has been renamed to .setFromProjectionMatrix().' ); return this.setFromProjectionMatrix( m ); }; Line3.prototype.center = function ( optionalTarget ) { console.warn( 'THREE.Line3: .center() has been renamed to .getCenter().' ); return this.getCenter( optionalTarget ); }; Object.assign( MathUtils, { random16: function () { console.warn( 'THREE.Math: .random16() has been deprecated. Use Math.random() instead.' ); return Math.random(); }, nearestPowerOfTwo: function ( value ) { console.warn( 'THREE.Math: .nearestPowerOfTwo() has been renamed to .floorPowerOfTwo().' ); return MathUtils.floorPowerOfTwo( value ); }, nextPowerOfTwo: function ( value ) { console.warn( 'THREE.Math: .nextPowerOfTwo() has been renamed to .ceilPowerOfTwo().' ); return MathUtils.ceilPowerOfTwo( value ); } } ); Object.assign( Matrix3.prototype, { flattenToArrayOffset: function ( array, offset ) { console.warn( "THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead." ); return this.toArray( array, offset ); }, multiplyVector3: function ( vector ) { console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' ); return vector.applyMatrix3( this ); }, multiplyVector3Array: function ( /* a */ ) { console.error( 'THREE.Matrix3: .multiplyVector3Array() has been removed.' ); }, applyToBufferAttribute: function ( attribute ) { console.warn( 'THREE.Matrix3: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix3( matrix ) instead.' ); return attribute.applyMatrix3( this ); }, applyToVector3Array: function ( /* array, offset, length */ ) { console.error( 'THREE.Matrix3: .applyToVector3Array() has been removed.' ); } } ); Object.assign( Matrix4.prototype, { extractPosition: function ( m ) { console.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' ); return this.copyPosition( m ); }, flattenToArrayOffset: function ( array, offset ) { console.warn( "THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead." ); return this.toArray( array, offset ); }, getPosition: function () { console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' ); return new Vector3().setFromMatrixColumn( this, 3 ); }, setRotationFromQuaternion: function ( q ) { console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' ); return this.makeRotationFromQuaternion( q ); }, multiplyToArray: function () { console.warn( 'THREE.Matrix4: .multiplyToArray() has been removed.' ); }, multiplyVector3: function ( vector ) { console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.' ); return vector.applyMatrix4( this ); }, multiplyVector4: function ( vector ) { console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' ); return vector.applyMatrix4( this ); }, multiplyVector3Array: function ( /* a */ ) { console.error( 'THREE.Matrix4: .multiplyVector3Array() has been removed.' ); }, rotateAxis: function ( v ) { console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' ); v.transformDirection( this ); }, crossVector: function ( vector ) { console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' ); return vector.applyMatrix4( this ); }, translate: function () { console.error( 'THREE.Matrix4: .translate() has been removed.' ); }, rotateX: function () { console.error( 'THREE.Matrix4: .rotateX() has been removed.' ); }, rotateY: function () { console.error( 'THREE.Matrix4: .rotateY() has been removed.' ); }, rotateZ: function () { console.error( 'THREE.Matrix4: .rotateZ() has been removed.' ); }, rotateByAxis: function () { console.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' ); }, applyToBufferAttribute: function ( attribute ) { console.warn( 'THREE.Matrix4: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix4( matrix ) instead.' ); return attribute.applyMatrix4( this ); }, applyToVector3Array: function ( /* array, offset, length */ ) { console.error( 'THREE.Matrix4: .applyToVector3Array() has been removed.' ); }, makeFrustum: function ( left, right, bottom, top, near, far ) { console.warn( 'THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.' ); return this.makePerspective( left, right, top, bottom, near, far ); } } ); Plane.prototype.isIntersectionLine = function ( line ) { console.warn( 'THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().' ); return this.intersectsLine( line ); }; Quaternion.prototype.multiplyVector3 = function ( vector ) { console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' ); return vector.applyQuaternion( this ); }; Object.assign( Ray.prototype, { isIntersectionBox: function ( box ) { console.warn( 'THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().' ); return this.intersectsBox( box ); }, isIntersectionPlane: function ( plane ) { console.warn( 'THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().' ); return this.intersectsPlane( plane ); }, isIntersectionSphere: function ( sphere ) { console.warn( 'THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().' ); return this.intersectsSphere( sphere ); } } ); Object.assign( Triangle.prototype, { area: function () { console.warn( 'THREE.Triangle: .area() has been renamed to .getArea().' ); return this.getArea(); }, barycoordFromPoint: function ( point, target ) { console.warn( 'THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().' ); return this.getBarycoord( point, target ); }, midpoint: function ( target ) { console.warn( 'THREE.Triangle: .midpoint() has been renamed to .getMidpoint().' ); return this.getMidpoint( target ); }, normal: function ( target ) { console.warn( 'THREE.Triangle: .normal() has been renamed to .getNormal().' ); return this.getNormal( target ); }, plane: function ( target ) { console.warn( 'THREE.Triangle: .plane() has been renamed to .getPlane().' ); return this.getPlane( target ); } } ); Object.assign( Triangle, { barycoordFromPoint: function ( point, a, b, c, target ) { console.warn( 'THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().' ); return Triangle.getBarycoord( point, a, b, c, target ); }, normal: function ( a, b, c, target ) { console.warn( 'THREE.Triangle: .normal() has been renamed to .getNormal().' ); return Triangle.getNormal( a, b, c, target ); } } ); Object.assign( Shape.prototype, { extractAllPoints: function ( divisions ) { console.warn( 'THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.' ); return this.extractPoints( divisions ); }, extrude: function ( options ) { console.warn( 'THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.' ); return new ExtrudeGeometry( this, options ); }, makeGeometry: function ( options ) { console.warn( 'THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.' ); return new ShapeGeometry( this, options ); } } ); Object.assign( Vector2.prototype, { fromAttribute: function ( attribute, index, offset ) { console.warn( 'THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().' ); return this.fromBufferAttribute( attribute, index, offset ); }, distanceToManhattan: function ( v ) { console.warn( 'THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().' ); return this.manhattanDistanceTo( v ); }, lengthManhattan: function () { console.warn( 'THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().' ); return this.manhattanLength(); } } ); Object.assign( Vector3.prototype, { setEulerFromRotationMatrix: function () { console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' ); }, setEulerFromQuaternion: function () { console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' ); }, getPositionFromMatrix: function ( m ) { console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' ); return this.setFromMatrixPosition( m ); }, getScaleFromMatrix: function ( m ) { console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' ); return this.setFromMatrixScale( m ); }, getColumnFromMatrix: function ( index, matrix ) { console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' ); return this.setFromMatrixColumn( matrix, index ); }, applyProjection: function ( m ) { console.warn( 'THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.' ); return this.applyMatrix4( m ); }, fromAttribute: function ( attribute, index, offset ) { console.warn( 'THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().' ); return this.fromBufferAttribute( attribute, index, offset ); }, distanceToManhattan: function ( v ) { console.warn( 'THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().' ); return this.manhattanDistanceTo( v ); }, lengthManhattan: function () { console.warn( 'THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().' ); return this.manhattanLength(); } } ); Object.assign( Vector4.prototype, { fromAttribute: function ( attribute, index, offset ) { console.warn( 'THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().' ); return this.fromBufferAttribute( attribute, index, offset ); }, lengthManhattan: function () { console.warn( 'THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().' ); return this.manhattanLength(); } } ); // Object.assign( Geometry.prototype, { computeTangents: function () { console.error( 'THREE.Geometry: .computeTangents() has been removed.' ); }, computeLineDistances: function () { console.error( 'THREE.Geometry: .computeLineDistances() has been removed. Use THREE.Line.computeLineDistances() instead.' ); }, applyMatrix: function ( matrix ) { console.warn( 'THREE.Geometry: .applyMatrix() has been renamed to .applyMatrix4().' ); return this.applyMatrix4( matrix ); } } ); Object.assign( Object3D.prototype, { getChildByName: function ( name ) { console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' ); return this.getObjectByName( name ); }, renderDepth: function () { console.warn( 'THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.' ); }, translate: function ( distance, axis ) { console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' ); return this.translateOnAxis( axis, distance ); }, getWorldRotation: function () { console.error( 'THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.' ); }, applyMatrix: function ( matrix ) { console.warn( 'THREE.Object3D: .applyMatrix() has been renamed to .applyMatrix4().' ); return this.applyMatrix4( matrix ); } } ); Object.defineProperties( Object3D.prototype, { eulerOrder: { get: function () { console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' ); return this.rotation.order; }, set: function ( value ) { console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' ); this.rotation.order = value; } }, useQuaternion: { get: function () { console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' ); }, set: function () { console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' ); } } } ); Object.assign( Mesh.prototype, { setDrawMode: function () { console.error( 'THREE.Mesh: .setDrawMode() has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.' ); }, } ); Object.defineProperties( Mesh.prototype, { drawMode: { get: function () { console.error( 'THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode.' ); return TrianglesDrawMode; }, set: function () { console.error( 'THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.' ); } } } ); Object.defineProperties( LOD.prototype, { objects: { get: function () { console.warn( 'THREE.LOD: .objects has been renamed to .levels.' ); return this.levels; } } } ); Object.defineProperty( Skeleton.prototype, 'useVertexTexture', { get: function () { console.warn( 'THREE.Skeleton: useVertexTexture has been removed.' ); }, set: function () { console.warn( 'THREE.Skeleton: useVertexTexture has been removed.' ); } } ); SkinnedMesh.prototype.initBones = function () { console.error( 'THREE.SkinnedMesh: initBones() has been removed.' ); }; Object.defineProperty( Curve.prototype, '__arcLengthDivisions', { get: function () { console.warn( 'THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.' ); return this.arcLengthDivisions; }, set: function ( value ) { console.warn( 'THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.' ); this.arcLengthDivisions = value; } } ); // PerspectiveCamera.prototype.setLens = function ( focalLength, filmGauge ) { console.warn( "THREE.PerspectiveCamera.setLens is deprecated. " + "Use .setFocalLength and .filmGauge for a photographic setup." ); if ( filmGauge !== undefined ) { this.filmGauge = filmGauge; } this.setFocalLength( focalLength ); }; // Object.defineProperties( Light.prototype, { onlyShadow: { set: function () { console.warn( 'THREE.Light: .onlyShadow has been removed.' ); } }, shadowCameraFov: { set: function ( value ) { console.warn( 'THREE.Light: .shadowCameraFov is now .shadow.camera.fov.' ); this.shadow.camera.fov = value; } }, shadowCameraLeft: { set: function ( value ) { console.warn( 'THREE.Light: .shadowCameraLeft is now .shadow.camera.left.' ); this.shadow.camera.left = value; } }, shadowCameraRight: { set: function ( value ) { console.warn( 'THREE.Light: .shadowCameraRight is now .shadow.camera.right.' ); this.shadow.camera.right = value; } }, shadowCameraTop: { set: function ( value ) { console.warn( 'THREE.Light: .shadowCameraTop is now .shadow.camera.top.' ); this.shadow.camera.top = value; } }, shadowCameraBottom: { set: function ( value ) { console.warn( 'THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.' ); this.shadow.camera.bottom = value; } }, shadowCameraNear: { set: function ( value ) { console.warn( 'THREE.Light: .shadowCameraNear is now .shadow.camera.near.' ); this.shadow.camera.near = value; } }, shadowCameraFar: { set: function ( value ) { console.warn( 'THREE.Light: .shadowCameraFar is now .shadow.camera.far.' ); this.shadow.camera.far = value; } }, shadowCameraVisible: { set: function () { console.warn( 'THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.' ); } }, shadowBias: { set: function ( value ) { console.warn( 'THREE.Light: .shadowBias is now .shadow.bias.' ); this.shadow.bias = value; } }, shadowDarkness: { set: function () { console.warn( 'THREE.Light: .shadowDarkness has been removed.' ); } }, shadowMapWidth: { set: function ( value ) { console.warn( 'THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.' ); this.shadow.mapSize.width = value; } }, shadowMapHeight: { set: function ( value ) { console.warn( 'THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.' ); this.shadow.mapSize.height = value; } } } ); // Object.defineProperties( BufferAttribute.prototype, { length: { get: function () { console.warn( 'THREE.BufferAttribute: .length has been deprecated. Use .count instead.' ); return this.array.length; } }, dynamic: { get: function () { console.warn( 'THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.' ); return this.usage === DynamicDrawUsage; }, set: function ( /* value */ ) { console.warn( 'THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.' ); this.setUsage( DynamicDrawUsage ); } } } ); Object.assign( BufferAttribute.prototype, { setDynamic: function ( value ) { console.warn( 'THREE.BufferAttribute: .setDynamic() has been deprecated. Use .setUsage() instead.' ); this.setUsage( value === true ? DynamicDrawUsage : StaticDrawUsage ); return this; }, copyIndicesArray: function ( /* indices */ ) { console.error( 'THREE.BufferAttribute: .copyIndicesArray() has been removed.' ); }, setArray: function ( /* array */ ) { console.error( 'THREE.BufferAttribute: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers' ); } } ); Object.assign( BufferGeometry.prototype, { addIndex: function ( index ) { console.warn( 'THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().' ); this.setIndex( index ); }, addAttribute: function ( name, attribute ) { console.warn( 'THREE.BufferGeometry: .addAttribute() has been renamed to .setAttribute().' ); if ( ! ( attribute && attribute.isBufferAttribute ) && ! ( attribute && attribute.isInterleavedBufferAttribute ) ) { console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' ); return this.setAttribute( name, new BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) ); } if ( name === 'index' ) { console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' ); this.setIndex( attribute ); return this; } return this.setAttribute( name, attribute ); }, addDrawCall: function ( start, count, indexOffset ) { if ( indexOffset !== undefined ) { console.warn( 'THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.' ); } console.warn( 'THREE.BufferGeometry: .addDrawCall() is now .addGroup().' ); this.addGroup( start, count ); }, clearDrawCalls: function () { console.warn( 'THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().' ); this.clearGroups(); }, computeTangents: function () { console.warn( 'THREE.BufferGeometry: .computeTangents() has been removed.' ); }, computeOffsets: function () { console.warn( 'THREE.BufferGeometry: .computeOffsets() has been removed.' ); }, removeAttribute: function ( name ) { console.warn( 'THREE.BufferGeometry: .removeAttribute() has been renamed to .deleteAttribute().' ); return this.deleteAttribute( name ); }, applyMatrix: function ( matrix ) { console.warn( 'THREE.BufferGeometry: .applyMatrix() has been renamed to .applyMatrix4().' ); return this.applyMatrix4( matrix ); } } ); Object.defineProperties( BufferGeometry.prototype, { drawcalls: { get: function () { console.error( 'THREE.BufferGeometry: .drawcalls has been renamed to .groups.' ); return this.groups; } }, offsets: { get: function () { console.warn( 'THREE.BufferGeometry: .offsets has been renamed to .groups.' ); return this.groups; } } } ); Object.defineProperties( InterleavedBuffer.prototype, { dynamic: { get: function () { console.warn( 'THREE.InterleavedBuffer: .length has been deprecated. Use .usage instead.' ); return this.usage === DynamicDrawUsage; }, set: function ( value ) { console.warn( 'THREE.InterleavedBuffer: .length has been deprecated. Use .usage instead.' ); this.setUsage( value ); } } } ); Object.assign( InterleavedBuffer.prototype, { setDynamic: function ( value ) { console.warn( 'THREE.InterleavedBuffer: .setDynamic() has been deprecated. Use .setUsage() instead.' ); this.setUsage( value === true ? DynamicDrawUsage : StaticDrawUsage ); return this; }, setArray: function ( /* array */ ) { console.error( 'THREE.InterleavedBuffer: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers' ); } } ); // Object.assign( ExtrudeBufferGeometry.prototype, { getArrays: function () { console.error( 'THREE.ExtrudeBufferGeometry: .getArrays() has been removed.' ); }, addShapeList: function () { console.error( 'THREE.ExtrudeBufferGeometry: .addShapeList() has been removed.' ); }, addShape: function () { console.error( 'THREE.ExtrudeBufferGeometry: .addShape() has been removed.' ); } } ); // Object.defineProperties( Uniform.prototype, { dynamic: { set: function () { console.warn( 'THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.' ); } }, onUpdate: { value: function () { console.warn( 'THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.' ); return this; } } } ); // Object.defineProperties( Material.prototype, { wrapAround: { get: function () { console.warn( 'THREE.Material: .wrapAround has been removed.' ); }, set: function () { console.warn( 'THREE.Material: .wrapAround has been removed.' ); } }, overdraw: { get: function () { console.warn( 'THREE.Material: .overdraw has been removed.' ); }, set: function () { console.warn( 'THREE.Material: .overdraw has been removed.' ); } }, wrapRGB: { get: function () { console.warn( 'THREE.Material: .wrapRGB has been removed.' ); return new Color(); } }, shading: { get: function () { console.error( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' ); }, set: function ( value ) { console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' ); this.flatShading = ( value === FlatShading ); } }, stencilMask: { get: function () { console.warn( 'THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.' ); return this.stencilFuncMask; }, set: function ( value ) { console.warn( 'THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.' ); this.stencilFuncMask = value; } } } ); Object.defineProperties( MeshPhongMaterial.prototype, { metal: { get: function () { console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.' ); return false; }, set: function () { console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead' ); } } } ); Object.defineProperties( ShaderMaterial.prototype, { derivatives: { get: function () { console.warn( 'THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' ); return this.extensions.derivatives; }, set: function ( value ) { console.warn( 'THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' ); this.extensions.derivatives = value; } } } ); // Object.assign( WebGLRenderer.prototype, { clearTarget: function ( renderTarget, color, depth, stencil ) { console.warn( 'THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead.' ); this.setRenderTarget( renderTarget ); this.clear( color, depth, stencil ); }, animate: function ( callback ) { console.warn( 'THREE.WebGLRenderer: .animate() is now .setAnimationLoop().' ); this.setAnimationLoop( callback ); }, getCurrentRenderTarget: function () { console.warn( 'THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().' ); return this.getRenderTarget(); }, getMaxAnisotropy: function () { console.warn( 'THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().' ); return this.capabilities.getMaxAnisotropy(); }, getPrecision: function () { console.warn( 'THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.' ); return this.capabilities.precision; }, resetGLState: function () { console.warn( 'THREE.WebGLRenderer: .resetGLState() is now .state.reset().' ); return this.state.reset(); }, supportsFloatTextures: function () { console.warn( 'THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).' ); return this.extensions.get( 'OES_texture_float' ); }, supportsHalfFloatTextures: function () { console.warn( 'THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).' ); return this.extensions.get( 'OES_texture_half_float' ); }, supportsStandardDerivatives: function () { console.warn( 'THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).' ); return this.extensions.get( 'OES_standard_derivatives' ); }, supportsCompressedTextureS3TC: function () { console.warn( 'THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).' ); return this.extensions.get( 'WEBGL_compressed_texture_s3tc' ); }, supportsCompressedTexturePVRTC: function () { console.warn( 'THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).' ); return this.extensions.get( 'WEBGL_compressed_texture_pvrtc' ); }, supportsBlendMinMax: function () { console.warn( 'THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).' ); return this.extensions.get( 'EXT_blend_minmax' ); }, supportsVertexTextures: function () { console.warn( 'THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.' ); return this.capabilities.vertexTextures; }, supportsInstancedArrays: function () { console.warn( 'THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).' ); return this.extensions.get( 'ANGLE_instanced_arrays' ); }, enableScissorTest: function ( boolean ) { console.warn( 'THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().' ); this.setScissorTest( boolean ); }, initMaterial: function () { console.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' ); }, addPrePlugin: function () { console.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' ); }, addPostPlugin: function () { console.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' ); }, updateShadowMap: function () { console.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' ); }, setFaceCulling: function () { console.warn( 'THREE.WebGLRenderer: .setFaceCulling() has been removed.' ); }, allocTextureUnit: function () { console.warn( 'THREE.WebGLRenderer: .allocTextureUnit() has been removed.' ); }, setTexture: function () { console.warn( 'THREE.WebGLRenderer: .setTexture() has been removed.' ); }, setTexture2D: function () { console.warn( 'THREE.WebGLRenderer: .setTexture2D() has been removed.' ); }, setTextureCube: function () { console.warn( 'THREE.WebGLRenderer: .setTextureCube() has been removed.' ); }, getActiveMipMapLevel: function () { console.warn( 'THREE.WebGLRenderer: .getActiveMipMapLevel() is now .getActiveMipmapLevel().' ); return this.getActiveMipmapLevel(); } } ); Object.defineProperties( WebGLRenderer.prototype, { shadowMapEnabled: { get: function () { return this.shadowMap.enabled; }, set: function ( value ) { console.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' ); this.shadowMap.enabled = value; } }, shadowMapType: { get: function () { return this.shadowMap.type; }, set: function ( value ) { console.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' ); this.shadowMap.type = value; } }, shadowMapCullFace: { get: function () { console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.' ); return undefined; }, set: function ( /* value */ ) { console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.' ); } }, context: { get: function () { console.warn( 'THREE.WebGLRenderer: .context has been removed. Use .getContext() instead.' ); return this.getContext(); } }, vr: { get: function () { console.warn( 'THREE.WebGLRenderer: .vr has been renamed to .xr' ); return this.xr; } }, gammaInput: { get: function () { console.warn( 'THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.' ); return false; }, set: function () { console.warn( 'THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.' ); } }, gammaOutput: { get: function () { console.warn( 'THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.' ); return false; }, set: function ( value ) { console.warn( 'THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.' ); this.outputEncoding = ( value === true ) ? sRGBEncoding : LinearEncoding; } } } ); Object.defineProperties( WebGLShadowMap.prototype, { cullFace: { get: function () { console.warn( 'THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.' ); return undefined; }, set: function ( /* cullFace */ ) { console.warn( 'THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.' ); } }, renderReverseSided: { get: function () { console.warn( 'THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.' ); return undefined; }, set: function () { console.warn( 'THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.' ); } }, renderSingleSided: { get: function () { console.warn( 'THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.' ); return undefined; }, set: function () { console.warn( 'THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.' ); } } } ); function WebGLRenderTargetCube( width, height, options ) { console.warn( 'THREE.WebGLRenderTargetCube( width, height, options ) is now WebGLCubeRenderTarget( size, options ).' ); return new WebGLCubeRenderTarget( width, options ); } // Object.defineProperties( WebGLRenderTarget.prototype, { wrapS: { get: function () { console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' ); return this.texture.wrapS; }, set: function ( value ) { console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' ); this.texture.wrapS = value; } }, wrapT: { get: function () { console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' ); return this.texture.wrapT; }, set: function ( value ) { console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' ); this.texture.wrapT = value; } }, magFilter: { get: function () { console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' ); return this.texture.magFilter; }, set: function ( value ) { console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' ); this.texture.magFilter = value; } }, minFilter: { get: function () { console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' ); return this.texture.minFilter; }, set: function ( value ) { console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' ); this.texture.minFilter = value; } }, anisotropy: { get: function () { console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' ); return this.texture.anisotropy; }, set: function ( value ) { console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' ); this.texture.anisotropy = value; } }, offset: { get: function () { console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' ); return this.texture.offset; }, set: function ( value ) { console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' ); this.texture.offset = value; } }, repeat: { get: function () { console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' ); return this.texture.repeat; }, set: function ( value ) { console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' ); this.texture.repeat = value; } }, format: { get: function () { console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' ); return this.texture.format; }, set: function ( value ) { console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' ); this.texture.format = value; } }, type: { get: function () { console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' ); return this.texture.type; }, set: function ( value ) { console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' ); this.texture.type = value; } }, generateMipmaps: { get: function () { console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' ); return this.texture.generateMipmaps; }, set: function ( value ) { console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' ); this.texture.generateMipmaps = value; } } } ); // Object.defineProperties( Audio.prototype, { load: { value: function ( file ) { console.warn( 'THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.' ); var scope = this; var audioLoader = new AudioLoader(); audioLoader.load( file, function ( buffer ) { scope.setBuffer( buffer ); } ); return this; } }, startTime: { set: function () { console.warn( 'THREE.Audio: .startTime is now .play( delay ).' ); } } } ); AudioAnalyser.prototype.getData = function () { console.warn( 'THREE.AudioAnalyser: .getData() is now .getFrequencyData().' ); return this.getFrequencyData(); }; // CubeCamera.prototype.updateCubeMap = function ( renderer, scene ) { console.warn( 'THREE.CubeCamera: .updateCubeMap() is now .update().' ); return this.update( renderer, scene ); }; // var GeometryUtils = { merge: function ( geometry1, geometry2, materialIndexOffset ) { console.warn( 'THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.' ); var matrix; if ( geometry2.isMesh ) { geometry2.matrixAutoUpdate && geometry2.updateMatrix(); matrix = geometry2.matrix; geometry2 = geometry2.geometry; } geometry1.merge( geometry2, matrix, materialIndexOffset ); }, center: function ( geometry ) { console.warn( 'THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.' ); return geometry.center(); } }; ImageUtils.crossOrigin = undefined; ImageUtils.loadTexture = function ( url, mapping, onLoad, onError ) { console.warn( 'THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.' ); var loader = new TextureLoader(); loader.setCrossOrigin( this.crossOrigin ); var texture = loader.load( url, onLoad, undefined, onError ); if ( mapping ) { texture.mapping = mapping; } return texture; }; ImageUtils.loadTextureCube = function ( urls, mapping, onLoad, onError ) { console.warn( 'THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.' ); var loader = new CubeTextureLoader(); loader.setCrossOrigin( this.crossOrigin ); var texture = loader.load( urls, onLoad, undefined, onError ); if ( mapping ) { texture.mapping = mapping; } return texture; }; ImageUtils.loadCompressedTexture = function () { console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' ); }; ImageUtils.loadCompressedTextureCube = function () { console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' ); }; // function CanvasRenderer() { console.error( 'THREE.CanvasRenderer has been removed' ); } // function JSONLoader() { console.error( 'THREE.JSONLoader has been removed.' ); } // var SceneUtils = { createMultiMaterialObject: function ( /* geometry, materials */ ) { console.error( 'THREE.SceneUtils has been moved to /examples/js/utils/SceneUtils.js' ); }, detach: function ( /* child, parent, scene */ ) { console.error( 'THREE.SceneUtils has been moved to /examples/js/utils/SceneUtils.js' ); }, attach: function ( /* child, scene, parent */ ) { console.error( 'THREE.SceneUtils has been moved to /examples/js/utils/SceneUtils.js' ); } }; // function LensFlare() { console.error( 'THREE.LensFlare has been moved to /examples/js/objects/Lensflare.js' ); } if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) { /* eslint-disable no-undef */ __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: { revision: REVISION, } } ) ); /* eslint-enable no-undef */ } exports.ACESFilmicToneMapping = ACESFilmicToneMapping; exports.AddEquation = AddEquation; exports.AddOperation = AddOperation; exports.AdditiveBlending = AdditiveBlending; exports.AlphaFormat = AlphaFormat; exports.AlwaysDepth = AlwaysDepth; exports.AlwaysStencilFunc = AlwaysStencilFunc; exports.AmbientLight = AmbientLight; exports.AmbientLightProbe = AmbientLightProbe; exports.AnimationClip = AnimationClip; exports.AnimationLoader = AnimationLoader; exports.AnimationMixer = AnimationMixer; exports.AnimationObjectGroup = AnimationObjectGroup; exports.AnimationUtils = AnimationUtils; exports.ArcCurve = ArcCurve; exports.ArrayCamera = ArrayCamera; exports.ArrowHelper = ArrowHelper; exports.Audio = Audio; exports.AudioAnalyser = AudioAnalyser; exports.AudioContext = AudioContext; exports.AudioListener = AudioListener; exports.AudioLoader = AudioLoader; exports.AxesHelper = AxesHelper; exports.AxisHelper = AxisHelper; exports.BackSide = BackSide; exports.BasicDepthPacking = BasicDepthPacking; exports.BasicShadowMap = BasicShadowMap; exports.BinaryTextureLoader = BinaryTextureLoader; exports.Bone = Bone; exports.BooleanKeyframeTrack = BooleanKeyframeTrack; exports.BoundingBoxHelper = BoundingBoxHelper; exports.Box2 = Box2; exports.Box3 = Box3; exports.Box3Helper = Box3Helper; exports.BoxBufferGeometry = BoxBufferGeometry; exports.BoxGeometry = BoxGeometry; exports.BoxHelper = BoxHelper; exports.BufferAttribute = BufferAttribute; exports.BufferGeometry = BufferGeometry; exports.BufferGeometryLoader = BufferGeometryLoader; exports.ByteType = ByteType; exports.Cache = Cache; exports.Camera = Camera; exports.CameraHelper = CameraHelper; exports.CanvasRenderer = CanvasRenderer; exports.CanvasTexture = CanvasTexture; exports.CatmullRomCurve3 = CatmullRomCurve3; exports.CineonToneMapping = CineonToneMapping; exports.CircleBufferGeometry = CircleBufferGeometry; exports.CircleGeometry = CircleGeometry; exports.ClampToEdgeWrapping = ClampToEdgeWrapping; exports.Clock = Clock; exports.ClosedSplineCurve3 = ClosedSplineCurve3; exports.Color = Color; exports.ColorKeyframeTrack = ColorKeyframeTrack; exports.CompressedTexture = CompressedTexture; exports.CompressedTextureLoader = CompressedTextureLoader; exports.ConeBufferGeometry = ConeBufferGeometry; exports.ConeGeometry = ConeGeometry; exports.CubeCamera = CubeCamera; exports.CubeGeometry = BoxGeometry; exports.CubeReflectionMapping = CubeReflectionMapping; exports.CubeRefractionMapping = CubeRefractionMapping; exports.CubeTexture = CubeTexture; exports.CubeTextureLoader = CubeTextureLoader; exports.CubeUVReflectionMapping = CubeUVReflectionMapping; exports.CubeUVRefractionMapping = CubeUVRefractionMapping; exports.CubicBezierCurve = CubicBezierCurve; exports.CubicBezierCurve3 = CubicBezierCurve3; exports.CubicInterpolant = CubicInterpolant; exports.CullFaceBack = CullFaceBack; exports.CullFaceFront = CullFaceFront; exports.CullFaceFrontBack = CullFaceFrontBack; exports.CullFaceNone = CullFaceNone; exports.Curve = Curve; exports.CurvePath = CurvePath; exports.CustomBlending = CustomBlending; exports.CylinderBufferGeometry = CylinderBufferGeometry; exports.CylinderGeometry = CylinderGeometry; exports.Cylindrical = Cylindrical; exports.DataTexture = DataTexture; exports.DataTexture2DArray = DataTexture2DArray; exports.DataTexture3D = DataTexture3D; exports.DataTextureLoader = DataTextureLoader; exports.DecrementStencilOp = DecrementStencilOp; exports.DecrementWrapStencilOp = DecrementWrapStencilOp; exports.DefaultLoadingManager = DefaultLoadingManager; exports.DepthFormat = DepthFormat; exports.DepthStencilFormat = DepthStencilFormat; exports.DepthTexture = DepthTexture; exports.DirectionalLight = DirectionalLight; exports.DirectionalLightHelper = DirectionalLightHelper; exports.DirectionalLightShadow = DirectionalLightShadow; exports.DiscreteInterpolant = DiscreteInterpolant; exports.DodecahedronBufferGeometry = DodecahedronBufferGeometry; exports.DodecahedronGeometry = DodecahedronGeometry; exports.DoubleSide = DoubleSide; exports.DstAlphaFactor = DstAlphaFactor; exports.DstColorFactor = DstColorFactor; exports.DynamicBufferAttribute = DynamicBufferAttribute; exports.DynamicCopyUsage = DynamicCopyUsage; exports.DynamicDrawUsage = DynamicDrawUsage; exports.DynamicReadUsage = DynamicReadUsage; exports.EdgesGeometry = EdgesGeometry; exports.EdgesHelper = EdgesHelper; exports.EllipseCurve = EllipseCurve; exports.EqualDepth = EqualDepth; exports.EqualStencilFunc = EqualStencilFunc; exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping; exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping; exports.Euler = Euler; exports.EventDispatcher = EventDispatcher; exports.ExtrudeBufferGeometry = ExtrudeBufferGeometry; exports.ExtrudeGeometry = ExtrudeGeometry; exports.Face3 = Face3; exports.Face4 = Face4; exports.FaceColors = FaceColors; exports.FileLoader = FileLoader; exports.FlatShading = FlatShading; exports.Float32Attribute = Float32Attribute; exports.Float32BufferAttribute = Float32BufferAttribute; exports.Float64Attribute = Float64Attribute; exports.Float64BufferAttribute = Float64BufferAttribute; exports.FloatType = FloatType; exports.Fog = Fog; exports.FogExp2 = FogExp2; exports.Font = Font; exports.FontLoader = FontLoader; exports.FrontFaceDirectionCCW = FrontFaceDirectionCCW; exports.FrontFaceDirectionCW = FrontFaceDirectionCW; exports.FrontSide = FrontSide; exports.Frustum = Frustum; exports.GammaEncoding = GammaEncoding; exports.Geometry = Geometry; exports.GeometryUtils = GeometryUtils; exports.GreaterDepth = GreaterDepth; exports.GreaterEqualDepth = GreaterEqualDepth; exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc; exports.GreaterStencilFunc = GreaterStencilFunc; exports.GridHelper = GridHelper; exports.Group = Group; exports.HalfFloatType = HalfFloatType; exports.HemisphereLight = HemisphereLight; exports.HemisphereLightHelper = HemisphereLightHelper; exports.HemisphereLightProbe = HemisphereLightProbe; exports.IcosahedronBufferGeometry = IcosahedronBufferGeometry; exports.IcosahedronGeometry = IcosahedronGeometry; exports.ImageBitmapLoader = ImageBitmapLoader; exports.ImageLoader = ImageLoader; exports.ImageUtils = ImageUtils; exports.ImmediateRenderObject = ImmediateRenderObject; exports.IncrementStencilOp = IncrementStencilOp; exports.IncrementWrapStencilOp = IncrementWrapStencilOp; exports.InstancedBufferAttribute = InstancedBufferAttribute; exports.InstancedBufferGeometry = InstancedBufferGeometry; exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer; exports.InstancedMesh = InstancedMesh; exports.Int16Attribute = Int16Attribute; exports.Int16BufferAttribute = Int16BufferAttribute; exports.Int32Attribute = Int32Attribute; exports.Int32BufferAttribute = Int32BufferAttribute; exports.Int8Attribute = Int8Attribute; exports.Int8BufferAttribute = Int8BufferAttribute; exports.IntType = IntType; exports.InterleavedBuffer = InterleavedBuffer; exports.InterleavedBufferAttribute = InterleavedBufferAttribute; exports.Interpolant = Interpolant; exports.InterpolateDiscrete = InterpolateDiscrete; exports.InterpolateLinear = InterpolateLinear; exports.InterpolateSmooth = InterpolateSmooth; exports.InvertStencilOp = InvertStencilOp; exports.JSONLoader = JSONLoader; exports.KeepStencilOp = KeepStencilOp; exports.KeyframeTrack = KeyframeTrack; exports.LOD = LOD; exports.LatheBufferGeometry = LatheBufferGeometry; exports.LatheGeometry = LatheGeometry; exports.Layers = Layers; exports.LensFlare = LensFlare; exports.LessDepth = LessDepth; exports.LessEqualDepth = LessEqualDepth; exports.LessEqualStencilFunc = LessEqualStencilFunc; exports.LessStencilFunc = LessStencilFunc; exports.Light = Light; exports.LightProbe = LightProbe; exports.LightShadow = LightShadow; exports.Line = Line; exports.Line3 = Line3; exports.LineBasicMaterial = LineBasicMaterial; exports.LineCurve = LineCurve; exports.LineCurve3 = LineCurve3; exports.LineDashedMaterial = LineDashedMaterial; exports.LineLoop = LineLoop; exports.LinePieces = LinePieces; exports.LineSegments = LineSegments; exports.LineStrip = LineStrip; exports.LinearEncoding = LinearEncoding; exports.LinearFilter = LinearFilter; exports.LinearInterpolant = LinearInterpolant; exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter; exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter; exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter; exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter; exports.LinearToneMapping = LinearToneMapping; exports.Loader = Loader; exports.LoaderUtils = LoaderUtils; exports.LoadingManager = LoadingManager; exports.LogLuvEncoding = LogLuvEncoding; exports.LoopOnce = LoopOnce; exports.LoopPingPong = LoopPingPong; exports.LoopRepeat = LoopRepeat; exports.LuminanceAlphaFormat = LuminanceAlphaFormat; exports.LuminanceFormat = LuminanceFormat; exports.MOUSE = MOUSE; exports.Material = Material; exports.MaterialLoader = MaterialLoader; exports.Math = MathUtils; exports.MathUtils = MathUtils; exports.Matrix3 = Matrix3; exports.Matrix4 = Matrix4; exports.MaxEquation = MaxEquation; exports.Mesh = Mesh; exports.MeshBasicMaterial = MeshBasicMaterial; exports.MeshDepthMaterial = MeshDepthMaterial; exports.MeshDistanceMaterial = MeshDistanceMaterial; exports.MeshFaceMaterial = MeshFaceMaterial; exports.MeshLambertMaterial = MeshLambertMaterial; exports.MeshMatcapMaterial = MeshMatcapMaterial; exports.MeshNormalMaterial = MeshNormalMaterial; exports.MeshPhongMaterial = MeshPhongMaterial; exports.MeshPhysicalMaterial = MeshPhysicalMaterial; exports.MeshStandardMaterial = MeshStandardMaterial; exports.MeshToonMaterial = MeshToonMaterial; exports.MinEquation = MinEquation; exports.MirroredRepeatWrapping = MirroredRepeatWrapping; exports.MixOperation = MixOperation; exports.MultiMaterial = MultiMaterial; exports.MultiplyBlending = MultiplyBlending; exports.MultiplyOperation = MultiplyOperation; exports.NearestFilter = NearestFilter; exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter; exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter; exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter; exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter; exports.NeverDepth = NeverDepth; exports.NeverStencilFunc = NeverStencilFunc; exports.NoBlending = NoBlending; exports.NoColors = NoColors; exports.NoToneMapping = NoToneMapping; exports.NormalBlending = NormalBlending; exports.NotEqualDepth = NotEqualDepth; exports.NotEqualStencilFunc = NotEqualStencilFunc; exports.NumberKeyframeTrack = NumberKeyframeTrack; exports.Object3D = Object3D; exports.ObjectLoader = ObjectLoader; exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap; exports.OctahedronBufferGeometry = OctahedronBufferGeometry; exports.OctahedronGeometry = OctahedronGeometry; exports.OneFactor = OneFactor; exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor; exports.OneMinusDstColorFactor = OneMinusDstColorFactor; exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor; exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor; exports.OrthographicCamera = OrthographicCamera; exports.PCFShadowMap = PCFShadowMap; exports.PCFSoftShadowMap = PCFSoftShadowMap; exports.PMREMGenerator = PMREMGenerator; exports.ParametricBufferGeometry = ParametricBufferGeometry; exports.ParametricGeometry = ParametricGeometry; exports.Particle = Particle; exports.ParticleBasicMaterial = ParticleBasicMaterial; exports.ParticleSystem = ParticleSystem; exports.ParticleSystemMaterial = ParticleSystemMaterial; exports.Path = Path; exports.PerspectiveCamera = PerspectiveCamera; exports.Plane = Plane; exports.PlaneBufferGeometry = PlaneBufferGeometry; exports.PlaneGeometry = PlaneGeometry; exports.PlaneHelper = PlaneHelper; exports.PointCloud = PointCloud; exports.PointCloudMaterial = PointCloudMaterial; exports.PointLight = PointLight; exports.PointLightHelper = PointLightHelper; exports.Points = Points; exports.PointsMaterial = PointsMaterial; exports.PolarGridHelper = PolarGridHelper; exports.PolyhedronBufferGeometry = PolyhedronBufferGeometry; exports.PolyhedronGeometry = PolyhedronGeometry; exports.PositionalAudio = PositionalAudio; exports.PropertyBinding = PropertyBinding; exports.PropertyMixer = PropertyMixer; exports.QuadraticBezierCurve = QuadraticBezierCurve; exports.QuadraticBezierCurve3 = QuadraticBezierCurve3; exports.Quaternion = Quaternion; exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack; exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant; exports.REVISION = REVISION; exports.RGBADepthPacking = RGBADepthPacking; exports.RGBAFormat = RGBAFormat; exports.RGBAIntegerFormat = RGBAIntegerFormat; exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format; exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format; exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format; exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format; exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format; exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format; exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format; exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format; exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format; exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format; exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format; exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format; exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format; exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format; exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format; exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format; exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format; exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format; exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format; exports.RGBDEncoding = RGBDEncoding; exports.RGBEEncoding = RGBEEncoding; exports.RGBEFormat = RGBEFormat; exports.RGBFormat = RGBFormat; exports.RGBIntegerFormat = RGBIntegerFormat; exports.RGBM16Encoding = RGBM16Encoding; exports.RGBM7Encoding = RGBM7Encoding; exports.RGB_ETC1_Format = RGB_ETC1_Format; exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format; exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format; exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format; exports.RGFormat = RGFormat; exports.RGIntegerFormat = RGIntegerFormat; exports.RawShaderMaterial = RawShaderMaterial; exports.Ray = Ray; exports.Raycaster = Raycaster; exports.RectAreaLight = RectAreaLight; exports.RedFormat = RedFormat; exports.RedIntegerFormat = RedIntegerFormat; exports.ReinhardToneMapping = ReinhardToneMapping; exports.RepeatWrapping = RepeatWrapping; exports.ReplaceStencilOp = ReplaceStencilOp; exports.ReverseSubtractEquation = ReverseSubtractEquation; exports.RingBufferGeometry = RingBufferGeometry; exports.RingGeometry = RingGeometry; exports.Scene = Scene; exports.SceneUtils = SceneUtils; exports.ShaderChunk = ShaderChunk; exports.ShaderLib = ShaderLib; exports.ShaderMaterial = ShaderMaterial; exports.ShadowMaterial = ShadowMaterial; exports.Shape = Shape; exports.ShapeBufferGeometry = ShapeBufferGeometry; exports.ShapeGeometry = ShapeGeometry; exports.ShapePath = ShapePath; exports.ShapeUtils = ShapeUtils; exports.ShortType = ShortType; exports.Skeleton = Skeleton; exports.SkeletonHelper = SkeletonHelper; exports.SkinnedMesh = SkinnedMesh; exports.SmoothShading = SmoothShading; exports.Sphere = Sphere; exports.SphereBufferGeometry = SphereBufferGeometry; exports.SphereGeometry = SphereGeometry; exports.Spherical = Spherical; exports.SphericalHarmonics3 = SphericalHarmonics3; exports.SphericalReflectionMapping = SphericalReflectionMapping; exports.Spline = Spline; exports.SplineCurve = SplineCurve; exports.SplineCurve3 = SplineCurve3; exports.SpotLight = SpotLight; exports.SpotLightHelper = SpotLightHelper; exports.SpotLightShadow = SpotLightShadow; exports.Sprite = Sprite; exports.SpriteMaterial = SpriteMaterial; exports.SrcAlphaFactor = SrcAlphaFactor; exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor; exports.SrcColorFactor = SrcColorFactor; exports.StaticCopyUsage = StaticCopyUsage; exports.StaticDrawUsage = StaticDrawUsage; exports.StaticReadUsage = StaticReadUsage; exports.StereoCamera = StereoCamera; exports.StreamCopyUsage = StreamCopyUsage; exports.StreamDrawUsage = StreamDrawUsage; exports.StreamReadUsage = StreamReadUsage; exports.StringKeyframeTrack = StringKeyframeTrack; exports.SubtractEquation = SubtractEquation; exports.SubtractiveBlending = SubtractiveBlending; exports.TOUCH = TOUCH; exports.TangentSpaceNormalMap = TangentSpaceNormalMap; exports.TetrahedronBufferGeometry = TetrahedronBufferGeometry; exports.TetrahedronGeometry = TetrahedronGeometry; exports.TextBufferGeometry = TextBufferGeometry; exports.TextGeometry = TextGeometry; exports.Texture = Texture; exports.TextureLoader = TextureLoader; exports.TorusBufferGeometry = TorusBufferGeometry; exports.TorusGeometry = TorusGeometry; exports.TorusKnotBufferGeometry = TorusKnotBufferGeometry; exports.TorusKnotGeometry = TorusKnotGeometry; exports.Triangle = Triangle; exports.TriangleFanDrawMode = TriangleFanDrawMode; exports.TriangleStripDrawMode = TriangleStripDrawMode; exports.TrianglesDrawMode = TrianglesDrawMode; exports.TubeBufferGeometry = TubeBufferGeometry; exports.TubeGeometry = TubeGeometry; exports.UVMapping = UVMapping; exports.Uint16Attribute = Uint16Attribute; exports.Uint16BufferAttribute = Uint16BufferAttribute; exports.Uint32Attribute = Uint32Attribute; exports.Uint32BufferAttribute = Uint32BufferAttribute; exports.Uint8Attribute = Uint8Attribute; exports.Uint8BufferAttribute = Uint8BufferAttribute; exports.Uint8ClampedAttribute = Uint8ClampedAttribute; exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute; exports.Uncharted2ToneMapping = Uncharted2ToneMapping; exports.Uniform = Uniform; exports.UniformsLib = UniformsLib; exports.UniformsUtils = UniformsUtils; exports.UnsignedByteType = UnsignedByteType; exports.UnsignedInt248Type = UnsignedInt248Type; exports.UnsignedIntType = UnsignedIntType; exports.UnsignedShort4444Type = UnsignedShort4444Type; exports.UnsignedShort5551Type = UnsignedShort5551Type; exports.UnsignedShort565Type = UnsignedShort565Type; exports.UnsignedShortType = UnsignedShortType; exports.VSMShadowMap = VSMShadowMap; exports.Vector2 = Vector2; exports.Vector3 = Vector3; exports.Vector4 = Vector4; exports.VectorKeyframeTrack = VectorKeyframeTrack; exports.Vertex = Vertex; exports.VertexColors = VertexColors; exports.VideoTexture = VideoTexture; exports.WebGLCubeRenderTarget = WebGLCubeRenderTarget; exports.WebGLMultisampleRenderTarget = WebGLMultisampleRenderTarget; exports.WebGLRenderTarget = WebGLRenderTarget; exports.WebGLRenderTargetCube = WebGLRenderTargetCube; exports.WebGLRenderer = WebGLRenderer; exports.WebGLUtils = WebGLUtils; exports.WireframeGeometry = WireframeGeometry; exports.WireframeHelper = WireframeHelper; exports.WrapAroundEnding = WrapAroundEnding; exports.XHRLoader = XHRLoader; exports.ZeroCurvatureEnding = ZeroCurvatureEnding; exports.ZeroFactor = ZeroFactor; exports.ZeroSlopeEnding = ZeroSlopeEnding; exports.ZeroStencilOp = ZeroStencilOp; exports.sRGBEncoding = sRGBEncoding; Object.defineProperty(exports, '__esModule', { value: true }); }))); /***/ }), /* 13 */ /***/ (function(module, exports) { function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } module.exports = _asyncToGenerator; /***/ }), /* 14 */, /* 15 */ /***/ (function(module, exports, __webpack_require__) { var arrayWithHoles = __webpack_require__(93); var iterableToArrayLimit = __webpack_require__(94); var nonIterableRest = __webpack_require__(95); function _slicedToArray(arr, i) { return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || nonIterableRest(); } module.exports = _slicedToArray; /***/ }), /* 16 */ /***/ (function(module, exports, __webpack_require__) { var arrayWithoutHoles = __webpack_require__(122); var iterableToArray = __webpack_require__(123); var nonIterableSpread = __webpack_require__(124); function _toConsumableArray(arr) { return arrayWithoutHoles(arr) || iterableToArray(arr) || nonIterableSpread(); } module.exports = _toConsumableArray; /***/ }), /* 17 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return _extends; }); function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } /***/ }), /* 18 */ /***/ (function(module, exports) { function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } module.exports = _defineProperty; /***/ }), /* 19 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* WEBPACK VAR INJECTION */(function(Hammer) {/* harmony import */ var utils_merge__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3); var rangePan = function rangePan() { var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, _ref$properties = _ref.properties, propertiesProp = _ref$properties === void 0 ? {} : _ref$properties, _ref$scale = _ref.scale, scale = _ref$scale === void 0 ? 'x' : _ref$scale; var defaultProperties = { type: 'hammer', gestures: [{ type: 'Pan', options: { event: 'range', direction: Hammer.DIRECTION_HORIZONTAL }, events: { rangestart: function rangestart(e) { this.chart.component("".concat(scale, "-range")).emit('rangeStart', e); }, rangemove: function rangemove(e) { this.chart.component("".concat(scale, "-range")).emit('rangeMove', e); }, rangeend: function rangeend(e) { this.chart.component("".concat(scale, "-range")).emit('rangeEnd', e); } } }] }; if (scale === 'y') { defaultProperties.gestures[0].options.direction = Hammer.DIRECTION_VERTICAL; } var properties = Object(utils_merge__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"])(defaultProperties, propertiesProp); return properties; }; /* harmony default export */ __webpack_exports__["a"] = (rangePan); /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(64))) /***/ }), /* 20 */, /* 21 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var _interopRequireDefault = __webpack_require__(34); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _react = _interopRequireDefault(__webpack_require__(0)); var _createSvgIcon = _interopRequireDefault(__webpack_require__(44)); var _default = (0, _createSvgIcon.default)(_react.default.createElement("path", { d: "M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z" }), 'Check'); exports.default = _default; /***/ }), /* 22 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return _defineProperty; }); function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } /***/ }), /* 23 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; if (true) { module.exports = __webpack_require__(89); } else {} /***/ }), /* 24 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; // CONCATENATED MODULE: ./node_modules/@material-ui/styles/node_modules/@babel/runtime/helpers/esm/objectWithoutPropertiesLoose.js function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } // CONCATENATED MODULE: ./node_modules/@material-ui/styles/node_modules/@babel/runtime/helpers/esm/objectWithoutProperties.js /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return _objectWithoutProperties; }); function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; } /***/ }), /* 25 */, /* 26 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony import */ var _createMuiTheme__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(76); var defaultTheme = Object(_createMuiTheme__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"])(); /* harmony default export */ __webpack_exports__["a"] = (defaultTheme); /***/ }), /* 27 */ /***/ (function(module, exports, __webpack_require__) { var rng = __webpack_require__(119); var bytesToUuid = __webpack_require__(120); function v4(options, buf, offset) { var i = buf && offset || 0; if (typeof(options) == 'string') { buf = options === 'binary' ? new Array(16) : null; options = null; } options = options || {}; var rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` rnds[6] = (rnds[6] & 0x0f) | 0x40; rnds[8] = (rnds[8] & 0x3f) | 0x80; // Copy bytes to buffer, if provided if (buf) { for (var ii = 0; ii < 16; ++ii) { buf[i + ii] = rnds[ii]; } } return buf || bytesToUuid(rnds); } module.exports = v4; /***/ }), /* 28 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var _interopRequireDefault = __webpack_require__(34); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _react = _interopRequireDefault(__webpack_require__(0)); var _createSvgIcon = _interopRequireDefault(__webpack_require__(44)); var _default = (0, _createSvgIcon.default)(_react.default.createElement("path", { d: "M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z" }), 'Search'); exports.default = _default; /***/ }), /* 29 */, /* 30 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* globals Atomics, SharedArrayBuffer, */ var undefined; var $TypeError = TypeError; var $gOPD = Object.getOwnPropertyDescriptor; if ($gOPD) { try { $gOPD({}, ''); } catch (e) { $gOPD = null; // this is IE 8, which has a broken gOPD } } var throwTypeError = function () { throw new $TypeError(); }; var ThrowTypeError = $gOPD ? (function () { try { // eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties arguments.callee; // IE 8 does not throw here return throwTypeError; } catch (calleeThrows) { try { // IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '') return $gOPD(arguments, 'callee').get; } catch (gOPDthrows) { return throwTypeError; } } }()) : throwTypeError; var hasSymbols = __webpack_require__(42)(); var getProto = Object.getPrototypeOf || function (x) { return x.__proto__; }; // eslint-disable-line no-proto var generator; // = function * () {}; var generatorFunction = generator ? getProto(generator) : undefined; var asyncFn; // async function() {}; var asyncFunction = asyncFn ? asyncFn.constructor : undefined; var asyncGen; // async function * () {}; var asyncGenFunction = asyncGen ? getProto(asyncGen) : undefined; var asyncGenIterator = asyncGen ? asyncGen() : undefined; var TypedArray = typeof Uint8Array === 'undefined' ? undefined : getProto(Uint8Array); var INTRINSICS = { '%Array%': Array, '%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer, '%ArrayBufferPrototype%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer.prototype, '%ArrayIteratorPrototype%': hasSymbols ? getProto([][Symbol.iterator]()) : undefined, '%ArrayPrototype%': Array.prototype, '%ArrayProto_entries%': Array.prototype.entries, '%ArrayProto_forEach%': Array.prototype.forEach, '%ArrayProto_keys%': Array.prototype.keys, '%ArrayProto_values%': Array.prototype.values, '%AsyncFromSyncIteratorPrototype%': undefined, '%AsyncFunction%': asyncFunction, '%AsyncFunctionPrototype%': asyncFunction ? asyncFunction.prototype : undefined, '%AsyncGenerator%': asyncGen ? getProto(asyncGenIterator) : undefined, '%AsyncGeneratorFunction%': asyncGenFunction, '%AsyncGeneratorPrototype%': asyncGenFunction ? asyncGenFunction.prototype : undefined, '%AsyncIteratorPrototype%': asyncGenIterator && hasSymbols && Symbol.asyncIterator ? asyncGenIterator[Symbol.asyncIterator]() : undefined, '%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics, '%Boolean%': Boolean, '%BooleanPrototype%': Boolean.prototype, '%DataView%': typeof DataView === 'undefined' ? undefined : DataView, '%DataViewPrototype%': typeof DataView === 'undefined' ? undefined : DataView.prototype, '%Date%': Date, '%DatePrototype%': Date.prototype, '%decodeURI%': decodeURI, '%decodeURIComponent%': decodeURIComponent, '%encodeURI%': encodeURI, '%encodeURIComponent%': encodeURIComponent, '%Error%': Error, '%ErrorPrototype%': Error.prototype, '%eval%': eval, // eslint-disable-line no-eval '%EvalError%': EvalError, '%EvalErrorPrototype%': EvalError.prototype, '%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array, '%Float32ArrayPrototype%': typeof Float32Array === 'undefined' ? undefined : Float32Array.prototype, '%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array, '%Float64ArrayPrototype%': typeof Float64Array === 'undefined' ? undefined : Float64Array.prototype, '%Function%': Function, '%FunctionPrototype%': Function.prototype, '%Generator%': generator ? getProto(generator()) : undefined, '%GeneratorFunction%': generatorFunction, '%GeneratorPrototype%': generatorFunction ? generatorFunction.prototype : undefined, '%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array, '%Int8ArrayPrototype%': typeof Int8Array === 'undefined' ? undefined : Int8Array.prototype, '%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array, '%Int16ArrayPrototype%': typeof Int16Array === 'undefined' ? undefined : Int8Array.prototype, '%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array, '%Int32ArrayPrototype%': typeof Int32Array === 'undefined' ? undefined : Int32Array.prototype, '%isFinite%': isFinite, '%isNaN%': isNaN, '%IteratorPrototype%': hasSymbols ? getProto(getProto([][Symbol.iterator]())) : undefined, '%JSON%': typeof JSON === 'object' ? JSON : undefined, '%JSONParse%': typeof JSON === 'object' ? JSON.parse : undefined, '%Map%': typeof Map === 'undefined' ? undefined : Map, '%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols ? undefined : getProto(new Map()[Symbol.iterator]()), '%MapPrototype%': typeof Map === 'undefined' ? undefined : Map.prototype, '%Math%': Math, '%Number%': Number, '%NumberPrototype%': Number.prototype, '%Object%': Object, '%ObjectPrototype%': Object.prototype, '%ObjProto_toString%': Object.prototype.toString, '%ObjProto_valueOf%': Object.prototype.valueOf, '%parseFloat%': parseFloat, '%parseInt%': parseInt, '%Promise%': typeof Promise === 'undefined' ? undefined : Promise, '%PromisePrototype%': typeof Promise === 'undefined' ? undefined : Promise.prototype, '%PromiseProto_then%': typeof Promise === 'undefined' ? undefined : Promise.prototype.then, '%Promise_all%': typeof Promise === 'undefined' ? undefined : Promise.all, '%Promise_reject%': typeof Promise === 'undefined' ? undefined : Promise.reject, '%Promise_resolve%': typeof Promise === 'undefined' ? undefined : Promise.resolve, '%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy, '%RangeError%': RangeError, '%RangeErrorPrototype%': RangeError.prototype, '%ReferenceError%': ReferenceError, '%ReferenceErrorPrototype%': ReferenceError.prototype, '%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect, '%RegExp%': RegExp, '%RegExpPrototype%': RegExp.prototype, '%Set%': typeof Set === 'undefined' ? undefined : Set, '%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols ? undefined : getProto(new Set()[Symbol.iterator]()), '%SetPrototype%': typeof Set === 'undefined' ? undefined : Set.prototype, '%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer, '%SharedArrayBufferPrototype%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer.prototype, '%String%': String, '%StringIteratorPrototype%': hasSymbols ? getProto(''[Symbol.iterator]()) : undefined, '%StringPrototype%': String.prototype, '%Symbol%': hasSymbols ? Symbol : undefined, '%SymbolPrototype%': hasSymbols ? Symbol.prototype : undefined, '%SyntaxError%': SyntaxError, '%SyntaxErrorPrototype%': SyntaxError.prototype, '%ThrowTypeError%': ThrowTypeError, '%TypedArray%': TypedArray, '%TypedArrayPrototype%': TypedArray ? TypedArray.prototype : undefined, '%TypeError%': $TypeError, '%TypeErrorPrototype%': $TypeError.prototype, '%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array, '%Uint8ArrayPrototype%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array.prototype, '%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray, '%Uint8ClampedArrayPrototype%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray.prototype, '%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array, '%Uint16ArrayPrototype%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array.prototype, '%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array, '%Uint32ArrayPrototype%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array.prototype, '%URIError%': URIError, '%URIErrorPrototype%': URIError.prototype, '%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap, '%WeakMapPrototype%': typeof WeakMap === 'undefined' ? undefined : WeakMap.prototype, '%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet, '%WeakSetPrototype%': typeof WeakSet === 'undefined' ? undefined : WeakSet.prototype }; var bind = __webpack_require__(40); var $replace = bind.call(Function.call, String.prototype.replace); /* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */ var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g; var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */ var stringToPath = function stringToPath(string) { var result = []; $replace(string, rePropName, function (match, number, quote, subString) { result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : (number || match); }); return result; }; /* end adaptation */ var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) { if (!(name in INTRINSICS)) { throw new SyntaxError('intrinsic ' + name + ' does not exist!'); } // istanbul ignore if // hopefully this is impossible to test :-) if (typeof INTRINSICS[name] === 'undefined' && !allowMissing) { throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!'); } return INTRINSICS[name]; }; module.exports = function GetIntrinsic(name, allowMissing) { if (typeof name !== 'string' || name.length === 0) { throw new TypeError('intrinsic name must be a non-empty string'); } if (arguments.length > 1 && typeof allowMissing !== 'boolean') { throw new TypeError('"allowMissing" argument must be a boolean'); } var parts = stringToPath(name); var value = getBaseIntrinsic('%' + (parts.length > 0 ? parts[0] : '') + '%', allowMissing); for (var i = 1; i < parts.length; i += 1) { if (value != null) { if ($gOPD && (i + 1) >= parts.length) { var desc = $gOPD(value, parts[i]); if (!allowMissing && !(parts[i] in value)) { throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.'); } value = desc ? (desc.get || desc.value) : value[parts[i]]; } else { value = value[parts[i]]; } } } return value; }; /***/ }), /* 31 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* unused harmony export easing */ /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return duration; }); /* harmony import */ var _babel_runtime_helpers_esm_objectWithoutProperties__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(4); // Follow https://material.google.com/motion/duration-easing.html#duration-easing-natural-easing-curves // to learn the context in which each easing should be used. var easing = { // This is the most common easing curve. easeInOut: 'cubic-bezier(0.4, 0, 0.2, 1)', // Objects enter the screen at full velocity from off-screen and // slowly decelerate to a resting point. easeOut: 'cubic-bezier(0.0, 0, 0.2, 1)', // Objects leave the screen at full velocity. They do not decelerate when off-screen. easeIn: 'cubic-bezier(0.4, 0, 1, 1)', // The sharp curve is used by objects that may return to the screen at any time. sharp: 'cubic-bezier(0.4, 0, 0.6, 1)' }; // Follow https://material.io/guidelines/motion/duration-easing.html#duration-easing-common-durations // to learn when use what timing var duration = { shortest: 150, shorter: 200, short: 250, // most basic recommended timing standard: 300, // this is to be used in complex animations complex: 375, // recommended when something is entering screen enteringScreen: 225, // recommended when something is leaving screen leavingScreen: 195 }; function formatMs(milliseconds) { return "".concat(Math.round(milliseconds), "ms"); } /** * @param {string|Array} props * @param {object} param * @param {string} param.prop * @param {number} param.duration * @param {string} param.easing * @param {number} param.delay */ /* harmony default export */ __webpack_exports__["a"] = ({ easing: easing, duration: duration, create: function create() { var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ['all']; var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var _options$duration = options.duration, durationOption = _options$duration === void 0 ? duration.standard : _options$duration, _options$easing = options.easing, easingOption = _options$easing === void 0 ? easing.easeInOut : _options$easing, _options$delay = options.delay, delay = _options$delay === void 0 ? 0 : _options$delay, other = Object(_babel_runtime_helpers_esm_objectWithoutProperties__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"])(options, ["duration", "easing", "delay"]); if (false) { var isNumber, isString; } return (Array.isArray(props) ? props : [props]).map(function (animatedProp) { return "".concat(animatedProp, " ").concat(typeof durationOption === 'string' ? durationOption : formatMs(durationOption), " ").concat(easingOption, " ").concat(typeof delay === 'string' ? delay : formatMs(delay)); }).join(','); }, getAutoHeightDuration: function getAutoHeightDuration(height) { if (!height) { return 0; } var constant = height / 36; // https://www.wolframalpha.com/input/?i=(4+%2B+15+*+(x+%2F+36+)+**+0.25+%2B+(x+%2F+36)+%2F+5)+*+10 return Math.round((4 + 15 * Math.pow(constant, 0.25) + constant / 5) * 10); } }); /***/ }), /* 32 */ /***/ (function(module, exports, __webpack_require__) { /* Mapbox GL JS is licensed under the 3-Clause BSD License. Full text of license: https://github.com/mapbox/mapbox-gl-js/blob/v1.10.1/LICENSE.txt */ (function (global, factory) { true ? module.exports = factory() : undefined; }(this, (function () { 'use strict'; /* eslint-disable */ var shared, worker, mapboxgl; // define gets called three times: one for each chunk. we rely on the order // they're imported to know which is which function define(_, chunk) { if (!shared) { shared = chunk; } else if (!worker) { worker = chunk; } else { var workerBundleString = 'var sharedChunk = {}; (' + shared + ')(sharedChunk); (' + worker + ')(sharedChunk);' var sharedChunk = {}; shared(sharedChunk); mapboxgl = chunk(sharedChunk); mapboxgl.workerUrl = window.URL.createObjectURL(new Blob([workerBundleString], { type: 'text/javascript' })); } } define(["exports"],(function(t){"use strict";function e(t,e){return t(e={exports:{}},e.exports),e.exports}var r=n;function n(t,e,r,n){this.cx=3*t,this.bx=3*(r-t)-this.cx,this.ax=1-this.cx-this.bx,this.cy=3*e,this.by=3*(n-e)-this.cy,this.ay=1-this.cy-this.by,this.p1x=t,this.p1y=n,this.p2x=r,this.p2y=n;}n.prototype.sampleCurveX=function(t){return ((this.ax*t+this.bx)*t+this.cx)*t},n.prototype.sampleCurveY=function(t){return ((this.ay*t+this.by)*t+this.cy)*t},n.prototype.sampleCurveDerivativeX=function(t){return (3*this.ax*t+2*this.bx)*t+this.cx},n.prototype.solveCurveX=function(t,e){var r,n,i,a,o;for(void 0===e&&(e=1e-6),i=t,o=0;o<8;o++){if(a=this.sampleCurveX(i)-t,Math.abs(a)(n=1))return n;for(;ra?r=i:n=i,i=.5*(n-r)+r;}return i},n.prototype.solve=function(t,e){return this.sampleCurveY(this.solveCurveX(t,e))};var i=a;function a(t,e){this.x=t,this.y=e;}function o(t,e,n,i){var a=new r(t,e,n,i);return function(t){return a.solve(t)}}a.prototype={clone:function(){return new a(this.x,this.y)},add:function(t){return this.clone()._add(t)},sub:function(t){return this.clone()._sub(t)},multByPoint:function(t){return this.clone()._multByPoint(t)},divByPoint:function(t){return this.clone()._divByPoint(t)},mult:function(t){return this.clone()._mult(t)},div:function(t){return this.clone()._div(t)},rotate:function(t){return this.clone()._rotate(t)},rotateAround:function(t,e){return this.clone()._rotateAround(t,e)},matMult:function(t){return this.clone()._matMult(t)},unit:function(){return this.clone()._unit()},perp:function(){return this.clone()._perp()},round:function(){return this.clone()._round()},mag:function(){return Math.sqrt(this.x*this.x+this.y*this.y)},equals:function(t){return this.x===t.x&&this.y===t.y},dist:function(t){return Math.sqrt(this.distSqr(t))},distSqr:function(t){var e=t.x-this.x,r=t.y-this.y;return e*e+r*r},angle:function(){return Math.atan2(this.y,this.x)},angleTo:function(t){return Math.atan2(this.y-t.y,this.x-t.x)},angleWith:function(t){return this.angleWithSep(t.x,t.y)},angleWithSep:function(t,e){return Math.atan2(this.x*e-this.y*t,this.x*t+this.y*e)},_matMult:function(t){var e=t[2]*this.x+t[3]*this.y;return this.x=t[0]*this.x+t[1]*this.y,this.y=e,this},_add:function(t){return this.x+=t.x,this.y+=t.y,this},_sub:function(t){return this.x-=t.x,this.y-=t.y,this},_mult:function(t){return this.x*=t,this.y*=t,this},_div:function(t){return this.x/=t,this.y/=t,this},_multByPoint:function(t){return this.x*=t.x,this.y*=t.y,this},_divByPoint:function(t){return this.x/=t.x,this.y/=t.y,this},_unit:function(){return this._div(this.mag()),this},_perp:function(){var t=this.y;return this.y=this.x,this.x=-t,this},_rotate:function(t){var e=Math.cos(t),r=Math.sin(t),n=r*this.x+e*this.y;return this.x=e*this.x-r*this.y,this.y=n,this},_rotateAround:function(t,e){var r=Math.cos(t),n=Math.sin(t),i=e.y+n*(this.x-e.x)+r*(this.y-e.y);return this.x=e.x+r*(this.x-e.x)-n*(this.y-e.y),this.y=i,this},_round:function(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}},a.convert=function(t){return t instanceof a?t:Array.isArray(t)?new a(t[0],t[1]):t};var s=o(.25,.1,.25,1);function u(t,e,r){return Math.min(r,Math.max(e,t))}function l(t,e,r){var n=r-e,i=((t-e)%n+n)%n+e;return i===e?r:i}function p(t){for(var e=[],r=arguments.length-1;r-- >0;)e[r]=arguments[r+1];for(var n=0,i=e;n>e/4).toString(16):([1e7]+-[1e3]+-4e3+-8e3+-1e11).replace(/[018]/g,t)}()}function y(t){return !!t&&/^[0-9a-f]{8}-[0-9a-f]{4}-[4][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(t)}function d(t,e){t.forEach((function(t){e[t]&&(e[t]=e[t].bind(e));}));}function m(t,e){return -1!==t.indexOf(e,t.length-e.length)}function v(t,e,r){var n={};for(var i in t)n[i]=e.call(r||this,t[i],i,t);return n}function g(t,e,r){var n={};for(var i in t)e.call(r||this,t[i],i,t)&&(n[i]=t[i]);return n}function x(t){return Array.isArray(t)?t.map(x):"object"==typeof t&&t?v(t,x):t}var b={};function w(t){b[t]||("undefined"!=typeof console&&console.warn(t),b[t]=!0);}function _(t,e,r){return (r.y-t.y)*(e.x-t.x)>(e.y-t.y)*(r.x-t.x)}function A(t){for(var e=0,r=0,n=t.length,i=n-1,a=void 0,o=void 0;r@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)(?:\=(?:([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)|(?:\"((?:[^"\\]|\\.)*)\")))?/g,(function(t,r,n,i){var a=n||i;return e[r]=!a||a.toLowerCase(),""})),e["max-age"]){var r=parseInt(e["max-age"],10);isNaN(r)?delete e["max-age"]:e["max-age"]=r;}return e}var I=null;function z(t){if(null==I){var e=t.navigator?t.navigator.userAgent:null;I=!!t.safari||!(!e||!(/\b(iPad|iPhone|iPod)\b/.test(e)||e.match("Safari")&&!e.match("Chrome")));}return I}function C(t){try{var e=self[t];return e.setItem("_mapbox_test_",1),e.removeItem("_mapbox_test_"),!0}catch(t){return !1}}var M,E,T,P,B=self.performance&&self.performance.now?self.performance.now.bind(self.performance):Date.now.bind(Date),V=self.requestAnimationFrame||self.mozRequestAnimationFrame||self.webkitRequestAnimationFrame||self.msRequestAnimationFrame,F=self.cancelAnimationFrame||self.mozCancelAnimationFrame||self.webkitCancelAnimationFrame||self.msCancelAnimationFrame,D={now:B,frame:function(t){var e=V(t);return {cancel:function(){return F(e)}}},getImageData:function(t,e){void 0===e&&(e=0);var r=self.document.createElement("canvas"),n=r.getContext("2d");if(!n)throw new Error("failed to create canvas 2d context");return r.width=t.width,r.height=t.height,n.drawImage(t,0,0,t.width,t.height),n.getImageData(-e,-e,t.width+2*e,t.height+2*e)},resolveURL:function(t){return M||(M=self.document.createElement("a")),M.href=t,M.href},hardwareConcurrency:self.navigator.hardwareConcurrency||4,get devicePixelRatio(){return self.devicePixelRatio},get prefersReducedMotion(){return !!self.matchMedia&&(null==E&&(E=self.matchMedia("(prefers-reduced-motion: reduce)")),E.matches)}},L={API_URL:"https://api.mapbox.com",get EVENTS_URL(){return this.API_URL?0===this.API_URL.indexOf("https://api.mapbox.cn")?"https://events.mapbox.cn/events/v2":0===this.API_URL.indexOf("https://api.mapbox.com")?"https://events.mapbox.com/events/v2":null:null},FEEDBACK_URL:"https://apps.mapbox.com/feedback",REQUIRE_ACCESS_TOKEN:!0,ACCESS_TOKEN:null,MAX_PARALLEL_IMAGE_REQUESTS:16},R={supported:!1,testSupport:function(t){!O&&P&&(U?j(t):T=t);}},O=!1,U=!1;function j(t){var e=t.createTexture();t.bindTexture(t.TEXTURE_2D,e);try{if(t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,P),t.isContextLost())return;R.supported=!0;}catch(t){}t.deleteTexture(e),O=!0;}self.document&&((P=self.document.createElement("img")).onload=function(){T&&j(T),T=null,U=!0;},P.onerror=function(){O=!0,T=null;},P.src="data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAQAAAAfQ//73v/+BiOh/AAA=");var q="01",N=function(t,e){this._transformRequestFn=t,this._customAccessToken=e,this._createSkuToken();};function K(t){return 0===t.indexOf("mapbox:")}N.prototype._createSkuToken=function(){var t=function(){for(var t="",e=0;e<10;e++)t+="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"[Math.floor(62*Math.random())];return {token:["1",q,t].join(""),tokenExpiresAt:Date.now()+432e5}}();this._skuToken=t.token,this._skuTokenExpiresAt=t.tokenExpiresAt;},N.prototype._isSkuTokenExpired=function(){return Date.now()>this._skuTokenExpiresAt},N.prototype.transformRequest=function(t,e){return this._transformRequestFn&&this._transformRequestFn(t,e)||{url:t}},N.prototype.normalizeStyleURL=function(t,e){if(!K(t))return t;var r=J(t);return r.path="/styles/v1"+r.path,this._makeAPIURL(r,this._customAccessToken||e)},N.prototype.normalizeGlyphsURL=function(t,e){if(!K(t))return t;var r=J(t);return r.path="/fonts/v1"+r.path,this._makeAPIURL(r,this._customAccessToken||e)},N.prototype.normalizeSourceURL=function(t,e){if(!K(t))return t;var r=J(t);return r.path="/v4/"+r.authority+".json",r.params.push("secure"),this._makeAPIURL(r,this._customAccessToken||e)},N.prototype.normalizeSpriteURL=function(t,e,r,n){var i=J(t);return K(t)?(i.path="/styles/v1"+i.path+"/sprite"+e+r,this._makeAPIURL(i,this._customAccessToken||n)):(i.path+=""+e+r,H(i))},N.prototype.normalizeTileURL=function(t,e){if(this._isSkuTokenExpired()&&this._createSkuToken(),t&&!K(t))return t;var r=J(t);r.path=r.path.replace(/(\.(png|jpg)\d*)(?=$)/,(D.devicePixelRatio>=2||512===e?"@2x":"")+(R.supported?".webp":"$1")),r.path=r.path.replace(/^.+\/v4\//,"/"),r.path="/v4"+r.path;var n=this._customAccessToken||function(t){for(var e=0,r=t;e=1&&self.localStorage.setItem(e,JSON.stringify(this.eventData));}catch(t){w("Unable to write to LocalStorage");}},$.prototype.processRequests=function(t){},$.prototype.postEvent=function(t,e,r,n){var i=this;if(L.EVENTS_URL){var a=J(L.EVENTS_URL);a.params.push("access_token="+(n||L.ACCESS_TOKEN||""));var o={event:this.type,created:new Date(t).toISOString(),sdkIdentifier:"mapbox-gl-js",sdkVersion:"1.10.1",skuId:q,userId:this.anonId},s=e?p(o,e):o,u={url:H(a),headers:{"Content-Type":"text/plain"},body:JSON.stringify([s])};this.pendingRequest=xt(u,(function(t){i.pendingRequest=null,r(t),i.saveEventData(),i.processRequests(n);}));}},$.prototype.queueRequest=function(t,e){this.queue.push(t),this.processRequests(e);};var W,Q,tt=function(t){function e(){t.call(this,"map.load"),this.success={},this.skuToken="";}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.postMapLoadEvent=function(t,e,r,n){this.skuToken=r,(L.EVENTS_URL&&n||L.ACCESS_TOKEN&&Array.isArray(t)&&t.some((function(t){return K(t)||Z(t)})))&&this.queueRequest({id:e,timestamp:Date.now()},n);},e.prototype.processRequests=function(t){var e=this;if(!this.pendingRequest&&0!==this.queue.length){var r=this.queue.shift(),n=r.id,i=r.timestamp;n&&this.success[n]||(this.anonId||this.fetchEventData(),y(this.anonId)||(this.anonId=f()),this.postEvent(i,{skuToken:this.skuToken},(function(t){t||n&&(e.success[n]=!0);}),t));}},e}($),et=new(function(t){function e(e){t.call(this,"appUserTurnstile"),this._customAccessToken=e;}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.postTurnstileEvent=function(t,e){L.EVENTS_URL&&L.ACCESS_TOKEN&&Array.isArray(t)&&t.some((function(t){return K(t)||Z(t)}))&&this.queueRequest(Date.now(),e);},e.prototype.processRequests=function(t){var e=this;if(!this.pendingRequest&&0!==this.queue.length){this.anonId&&this.eventData.lastSuccess&&this.eventData.tokenU||this.fetchEventData();var r=Y(L.ACCESS_TOKEN),n=r?r.u:L.ACCESS_TOKEN,i=n!==this.eventData.tokenU;y(this.anonId)||(this.anonId=f(),i=!0);var a=this.queue.shift();if(this.eventData.lastSuccess){var o=new Date(this.eventData.lastSuccess),s=new Date(a),u=(a-this.eventData.lastSuccess)/864e5;i=i||u>=1||u<-1||o.getDate()!==s.getDate();}else i=!0;if(!i)return this.processRequests();this.postEvent(a,{"enabled.telemetry":!1},(function(t){t||(e.eventData.lastSuccess=a,e.eventData.tokenU=n);}),t);}},e}($)),rt=et.postTurnstileEvent.bind(et),nt=new tt,it=nt.postMapLoadEvent.bind(nt),at=500,ot=50;function st(){self.caches&&!W&&(W=self.caches.open("mapbox-tiles"));}function ut(t){var e=t.indexOf("?");return e<0?t:t.slice(0,e)}var lt,pt=1/0;function ct(){return null==lt&&(lt=self.OffscreenCanvas&&new self.OffscreenCanvas(1,1).getContext("2d")&&"function"==typeof self.createImageBitmap),lt}var ht={Unknown:"Unknown",Style:"Style",Source:"Source",Tile:"Tile",Glyphs:"Glyphs",SpriteImage:"SpriteImage",SpriteJSON:"SpriteJSON",Image:"Image"};"function"==typeof Object.freeze&&Object.freeze(ht);var ft=function(t){function e(e,r,n){401===r&&Z(n)&&(e+=": you may have provided an invalid Mapbox access token. See https://www.mapbox.com/api-documentation/#access-tokens-and-token-scopes"),t.call(this,e),this.status=r,this.url=n,this.name=this.constructor.name,this.message=e;}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.toString=function(){return this.name+": "+this.message+" ("+this.status+"): "+this.url},e}(Error),yt=S()?function(){return self.worker&&self.worker.referrer}:function(){return ("blob:"===self.location.protocol?self.parent:self).location.href};var dt,mt,vt=function(t,e){if(!(/^file:/.test(r=t.url)||/^file:/.test(yt())&&!/^\w+:/.test(r))){if(self.fetch&&self.Request&&self.AbortController&&self.Request.prototype.hasOwnProperty("signal"))return function(t,e){var r,n=new self.AbortController,i=new self.Request(t.url,{method:t.method||"GET",body:t.body,credentials:t.credentials,headers:t.headers,referrer:yt(),signal:n.signal}),a=!1,o=!1,s=(r=i.url).indexOf("sku=")>0&&Z(r);"json"===t.type&&i.headers.set("Accept","application/json");var u=function(r,n,a){if(!o){if(r&&"SecurityError"!==r.message&&w(r),n&&a)return l(n);var u=Date.now();self.fetch(i).then((function(r){if(r.ok){var n=s?r.clone():null;return l(r,n,u)}return e(new ft(r.statusText,r.status,t.url))})).catch((function(t){20!==t.code&&e(new Error(t.message));}));}},l=function(r,n,s){("arrayBuffer"===t.type?r.arrayBuffer():"json"===t.type?r.json():r.text()).then((function(t){o||(n&&s&&function(t,e,r){if(st(),W){var n={status:e.status,statusText:e.statusText,headers:new self.Headers};e.headers.forEach((function(t,e){return n.headers.set(e,t)}));var i=k(e.headers.get("Cache-Control")||"");i["no-store"]||(i["max-age"]&&n.headers.set("Expires",new Date(r+1e3*i["max-age"]).toUTCString()),new Date(n.headers.get("Expires")).getTime()-r<42e4||function(t,e){if(void 0===Q)try{new Response(new ReadableStream),Q=!0;}catch(t){Q=!1;}Q?e(t.body):t.blob().then(e);}(e,(function(e){var r=new self.Response(e,n);st(),W&&W.then((function(e){return e.put(ut(t.url),r)})).catch((function(t){return w(t.message)}));})));}}(i,n,s),a=!0,e(null,t,r.headers.get("Cache-Control"),r.headers.get("Expires")));})).catch((function(t){o||e(new Error(t.message));}));};return s?function(t,e){if(st(),!W)return e(null);var r=ut(t.url);W.then((function(t){t.match(r).then((function(n){var i=function(t){if(!t)return !1;var e=new Date(t.headers.get("Expires")||0),r=k(t.headers.get("Cache-Control")||"");return e>Date.now()&&!r["no-cache"]}(n);t.delete(r),i&&t.put(r,n.clone()),e(null,n,i);})).catch(e);})).catch(e);}(i,u):u(null,null),{cancel:function(){o=!0,a||n.abort();}}}(t,e);if(S()&&self.worker&&self.worker.actor)return self.worker.actor.send("getResource",t,e,void 0,!0)}var r;return function(t,e){var r=new self.XMLHttpRequest;for(var n in r.open(t.method||"GET",t.url,!0),"arrayBuffer"===t.type&&(r.responseType="arraybuffer"),t.headers)r.setRequestHeader(n,t.headers[n]);return "json"===t.type&&(r.responseType="text",r.setRequestHeader("Accept","application/json")),r.withCredentials="include"===t.credentials,r.onerror=function(){e(new Error(r.statusText));},r.onload=function(){if((r.status>=200&&r.status<300||0===r.status)&&null!==r.response){var n=r.response;if("json"===t.type)try{n=JSON.parse(r.response);}catch(t){return e(t)}e(null,n,r.getResponseHeader("Cache-Control"),r.getResponseHeader("Expires"));}else e(new ft(r.statusText,r.status,t.url));},r.send(t.body),{cancel:function(){return r.abort()}}}(t,e)},gt=function(t,e){return vt(p(t,{type:"arrayBuffer"}),e)},xt=function(t,e){return vt(p(t,{method:"POST"}),e)};dt=[],mt=0;var bt=function(t,e){if(R.supported&&(t.headers||(t.headers={}),t.headers.accept="image/webp,*/*"),mt>=L.MAX_PARALLEL_IMAGE_REQUESTS){var r={requestParameters:t,callback:e,cancelled:!1,cancel:function(){this.cancelled=!0;}};return dt.push(r),r}mt++;var n=!1,i=function(){if(!n)for(n=!0,mt--;dt.length&&mt0||this._oneTimeListeners&&this._oneTimeListeners[t]&&this._oneTimeListeners[t].length>0||this._eventedParent&&this._eventedParent.listens(t)},kt.prototype.setEventedParent=function(t,e){return this._eventedParent=t,this._eventedParentData=e,this};var It={$version:8,$root:{version:{required:!0,type:"enum",values:[8]},name:{type:"string"},metadata:{type:"*"},center:{type:"array",value:"number"},zoom:{type:"number"},bearing:{type:"number",default:0,period:360,units:"degrees"},pitch:{type:"number",default:0,units:"degrees"},light:{type:"light"},sources:{required:!0,type:"sources"},sprite:{type:"string"},glyphs:{type:"string"},transition:{type:"transition"},layers:{required:!0,type:"array",value:"layer"}},sources:{"*":{type:"source"}},source:["source_vector","source_raster","source_raster_dem","source_geojson","source_video","source_image"],source_vector:{type:{required:!0,type:"enum",values:{vector:{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.051129,180,85.051129]},scheme:{type:"enum",values:{xyz:{},tms:{}},default:"xyz"},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},attribution:{type:"string"},promoteId:{type:"promoteId"},"*":{type:"*"}},source_raster:{type:{required:!0,type:"enum",values:{raster:{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.051129,180,85.051129]},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},tileSize:{type:"number",default:512,units:"pixels"},scheme:{type:"enum",values:{xyz:{},tms:{}},default:"xyz"},attribution:{type:"string"},"*":{type:"*"}},source_raster_dem:{type:{required:!0,type:"enum",values:{"raster-dem":{}}},url:{type:"string"},tiles:{type:"array",value:"string"},bounds:{type:"array",value:"number",length:4,default:[-180,-85.051129,180,85.051129]},minzoom:{type:"number",default:0},maxzoom:{type:"number",default:22},tileSize:{type:"number",default:512,units:"pixels"},attribution:{type:"string"},encoding:{type:"enum",values:{terrarium:{},mapbox:{}},default:"mapbox"},"*":{type:"*"}},source_geojson:{type:{required:!0,type:"enum",values:{geojson:{}}},data:{type:"*"},maxzoom:{type:"number",default:18},attribution:{type:"string"},buffer:{type:"number",default:128,maximum:512,minimum:0},tolerance:{type:"number",default:.375},cluster:{type:"boolean",default:!1},clusterRadius:{type:"number",default:50,minimum:0},clusterMaxZoom:{type:"number"},clusterProperties:{type:"*"},lineMetrics:{type:"boolean",default:!1},generateId:{type:"boolean",default:!1},promoteId:{type:"promoteId"}},source_video:{type:{required:!0,type:"enum",values:{video:{}}},urls:{required:!0,type:"array",value:"string"},coordinates:{required:!0,type:"array",length:4,value:{type:"array",length:2,value:"number"}}},source_image:{type:{required:!0,type:"enum",values:{image:{}}},url:{required:!0,type:"string"},coordinates:{required:!0,type:"array",length:4,value:{type:"array",length:2,value:"number"}}},layer:{id:{type:"string",required:!0},type:{type:"enum",values:{fill:{},line:{},symbol:{},circle:{},heatmap:{},"fill-extrusion":{},raster:{},hillshade:{},background:{}},required:!0},metadata:{type:"*"},source:{type:"string"},"source-layer":{type:"string"},minzoom:{type:"number",minimum:0,maximum:24},maxzoom:{type:"number",minimum:0,maximum:24},filter:{type:"filter"},layout:{type:"layout"},paint:{type:"paint"}},layout:["layout_fill","layout_line","layout_circle","layout_heatmap","layout_fill-extrusion","layout_symbol","layout_raster","layout_hillshade","layout_background"],layout_background:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_fill:{"fill-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_circle:{"circle-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_heatmap:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},"layout_fill-extrusion":{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_line:{"line-cap":{type:"enum",values:{butt:{},round:{},square:{}},default:"butt",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"line-join":{type:"enum",values:{bevel:{},round:{},miter:{}},default:"miter",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"line-miter-limit":{type:"number",default:2,requires:[{"line-join":"miter"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"line-round-limit":{type:"number",default:1.05,requires:[{"line-join":"round"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"line-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_symbol:{"symbol-placement":{type:"enum",values:{point:{},line:{},"line-center":{}},default:"point",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"symbol-spacing":{type:"number",default:250,minimum:1,units:"pixels",requires:[{"symbol-placement":"line"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"symbol-avoid-edges":{type:"boolean",default:!1,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"symbol-sort-key":{type:"number",expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"symbol-z-order":{type:"enum",values:{auto:{},"viewport-y":{},source:{}},default:"auto",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-allow-overlap":{type:"boolean",default:!1,requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-ignore-placement":{type:"boolean",default:!1,requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-optional":{type:"boolean",default:!1,requires:["icon-image","text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-rotation-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-size":{type:"number",default:1,minimum:0,units:"factor of the original icon size",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-text-fit":{type:"enum",values:{none:{},width:{},height:{},both:{}},default:"none",requires:["icon-image","text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-text-fit-padding":{type:"array",value:"number",length:4,default:[0,0,0,0],units:"pixels",requires:["icon-image","text-field",{"icon-text-fit":["both","width","height"]}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"icon-image":{type:"resolvedImage",tokens:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-rotate":{type:"number",default:0,period:360,units:"degrees",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-padding":{type:"number",default:2,minimum:0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"icon-keep-upright":{type:"boolean",default:!1,requires:["icon-image",{"icon-rotation-alignment":"map"},{"symbol-placement":["line","line-center"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"icon-offset":{type:"array",value:"number",length:2,default:[0,0],requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-anchor":{type:"enum",values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},default:"center",requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"icon-pitch-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-pitch-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-rotation-alignment":{type:"enum",values:{map:{},viewport:{},auto:{}},default:"auto",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-field":{type:"formatted",default:"",tokens:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-font":{type:"array",value:"string",default:["Open Sans Regular","Arial Unicode MS Regular"],requires:["text-field"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-size":{type:"number",default:16,minimum:0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-max-width":{type:"number",default:10,minimum:0,units:"ems",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-line-height":{type:"number",default:1.2,units:"ems",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-letter-spacing":{type:"number",default:0,units:"ems",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-justify":{type:"enum",values:{auto:{},left:{},center:{},right:{}},default:"center",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-radial-offset":{type:"number",units:"ems",default:0,requires:["text-field"],"property-type":"data-driven",expression:{interpolated:!0,parameters:["zoom","feature"]}},"text-variable-anchor":{type:"array",value:"enum",values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},requires:["text-field",{"symbol-placement":["point"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-anchor":{type:"enum",values:{center:{},left:{},right:{},top:{},bottom:{},"top-left":{},"top-right":{},"bottom-left":{},"bottom-right":{}},default:"center",requires:["text-field",{"!":"text-variable-anchor"}],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-max-angle":{type:"number",default:45,units:"degrees",requires:["text-field",{"symbol-placement":["line","line-center"]}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-writing-mode":{type:"array",value:"enum",values:{horizontal:{},vertical:{}},requires:["text-field",{"symbol-placement":["point"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-rotate":{type:"number",default:0,period:360,units:"degrees",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-padding":{type:"number",default:2,minimum:0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-keep-upright":{type:"boolean",default:!0,requires:["text-field",{"text-rotation-alignment":"map"},{"symbol-placement":["line","line-center"]}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-transform":{type:"enum",values:{none:{},uppercase:{},lowercase:{}},default:"none",requires:["text-field"],expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-offset":{type:"array",value:"number",units:"ems",length:2,default:[0,0],requires:["text-field",{"!":"text-radial-offset"}],expression:{interpolated:!0,parameters:["zoom","feature"]},"property-type":"data-driven"},"text-allow-overlap":{type:"boolean",default:!1,requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-ignore-placement":{type:"boolean",default:!1,requires:["text-field"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-optional":{type:"boolean",default:!1,requires:["text-field","icon-image"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_raster:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},layout_hillshade:{visibility:{type:"enum",values:{visible:{},none:{}},default:"visible","property-type":"constant"}},filter:{type:"array",value:"*"},filter_operator:{type:"enum",values:{"==":{},"!=":{},">":{},">=":{},"<":{},"<=":{},in:{},"!in":{},all:{},any:{},none:{},has:{},"!has":{},within:{}}},geometry_type:{type:"enum",values:{Point:{},LineString:{},Polygon:{}}},function:{expression:{type:"expression"},stops:{type:"array",value:"function_stop"},base:{type:"number",default:1,minimum:0},property:{type:"string",default:"$zoom"},type:{type:"enum",values:{identity:{},exponential:{},interval:{},categorical:{}},default:"exponential"},colorSpace:{type:"enum",values:{rgb:{},lab:{},hcl:{}},default:"rgb"},default:{type:"*",required:!1}},function_stop:{type:"array",minimum:0,maximum:24,value:["number","color"],length:2},expression:{type:"array",value:"*",minimum:1},expression_name:{type:"enum",values:{let:{group:"Variable binding"},var:{group:"Variable binding"},literal:{group:"Types"},array:{group:"Types"},at:{group:"Lookup"},in:{group:"Lookup"},"index-of":{group:"Lookup"},slice:{group:"Lookup"},case:{group:"Decision"},match:{group:"Decision"},coalesce:{group:"Decision"},step:{group:"Ramps, scales, curves"},interpolate:{group:"Ramps, scales, curves"},"interpolate-hcl":{group:"Ramps, scales, curves"},"interpolate-lab":{group:"Ramps, scales, curves"},ln2:{group:"Math"},pi:{group:"Math"},e:{group:"Math"},typeof:{group:"Types"},string:{group:"Types"},number:{group:"Types"},boolean:{group:"Types"},object:{group:"Types"},collator:{group:"Types"},format:{group:"Types"},image:{group:"Types"},"number-format":{group:"Types"},"to-string":{group:"Types"},"to-number":{group:"Types"},"to-boolean":{group:"Types"},"to-rgba":{group:"Color"},"to-color":{group:"Types"},rgb:{group:"Color"},rgba:{group:"Color"},get:{group:"Lookup"},has:{group:"Lookup"},length:{group:"Lookup"},properties:{group:"Feature data"},"feature-state":{group:"Feature data"},"geometry-type":{group:"Feature data"},id:{group:"Feature data"},zoom:{group:"Zoom"},"heatmap-density":{group:"Heatmap"},"line-progress":{group:"Feature data"},accumulated:{group:"Feature data"},"+":{group:"Math"},"*":{group:"Math"},"-":{group:"Math"},"/":{group:"Math"},"%":{group:"Math"},"^":{group:"Math"},sqrt:{group:"Math"},log10:{group:"Math"},ln:{group:"Math"},log2:{group:"Math"},sin:{group:"Math"},cos:{group:"Math"},tan:{group:"Math"},asin:{group:"Math"},acos:{group:"Math"},atan:{group:"Math"},min:{group:"Math"},max:{group:"Math"},round:{group:"Math"},abs:{group:"Math"},ceil:{group:"Math"},floor:{group:"Math"},distance:{group:"Math"},"==":{group:"Decision"},"!=":{group:"Decision"},">":{group:"Decision"},"<":{group:"Decision"},">=":{group:"Decision"},"<=":{group:"Decision"},all:{group:"Decision"},any:{group:"Decision"},"!":{group:"Decision"},within:{group:"Decision"},"is-supported-script":{group:"String"},upcase:{group:"String"},downcase:{group:"String"},concat:{group:"String"},"resolved-locale":{group:"String"}}},light:{anchor:{type:"enum",default:"viewport",values:{map:{},viewport:{}},"property-type":"data-constant",transition:!1,expression:{interpolated:!1,parameters:["zoom"]}},position:{type:"array",default:[1.15,210,30],length:3,value:"number","property-type":"data-constant",transition:!0,expression:{interpolated:!0,parameters:["zoom"]}},color:{type:"color","property-type":"data-constant",default:"#ffffff",expression:{interpolated:!0,parameters:["zoom"]},transition:!0},intensity:{type:"number","property-type":"data-constant",default:.5,minimum:0,maximum:1,expression:{interpolated:!0,parameters:["zoom"]},transition:!0}},paint:["paint_fill","paint_line","paint_circle","paint_heatmap","paint_fill-extrusion","paint_symbol","paint_raster","paint_hillshade","paint_background"],paint_fill:{"fill-antialias":{type:"boolean",default:!0,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"fill-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-outline-color":{type:"color",transition:!0,requires:[{"!":"fill-pattern"},{"fill-antialias":!0}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["fill-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"}},"paint_fill-extrusion":{"fill-extrusion-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"fill-extrusion-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["fill-extrusion-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"fill-extrusion-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"},"fill-extrusion-height":{type:"number",default:0,minimum:0,units:"meters",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-base":{type:"number",default:0,minimum:0,units:"meters",transition:!0,requires:["fill-extrusion-height"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"fill-extrusion-vertical-gradient":{type:"boolean",default:!0,transition:!1,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"}},paint_line:{"line-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"line-pattern"}],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"line-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["line-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"line-width":{type:"number",default:1,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-gap-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-offset":{type:"number",default:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"line-dasharray":{type:"array",value:"number",minimum:0,transition:!0,units:"line widths",requires:[{"!":"line-pattern"}],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"cross-faded"},"line-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom","feature"]},"property-type":"cross-faded-data-driven"},"line-gradient":{type:"color",transition:!1,requires:[{"!":"line-dasharray"},{"!":"line-pattern"},{source:"geojson",has:{lineMetrics:!0}}],expression:{interpolated:!0,parameters:["line-progress"]},"property-type":"color-ramp"}},paint_circle:{"circle-radius":{type:"number",default:5,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-blur":{type:"number",default:0,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"circle-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["circle-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-pitch-scale":{type:"enum",values:{map:{},viewport:{}},default:"map",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-pitch-alignment":{type:"enum",values:{map:{},viewport:{}},default:"viewport",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"circle-stroke-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-stroke-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"circle-stroke-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"}},paint_heatmap:{"heatmap-radius":{type:"number",default:30,minimum:1,transition:!0,units:"pixels",expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"heatmap-weight":{type:"number",default:1,minimum:0,transition:!1,expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"heatmap-intensity":{type:"number",default:1,minimum:0,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"heatmap-color":{type:"color",default:["interpolate",["linear"],["heatmap-density"],0,"rgba(0, 0, 255, 0)",.1,"royalblue",.3,"cyan",.5,"lime",.7,"yellow",1,"red"],transition:!1,expression:{interpolated:!0,parameters:["heatmap-density"]},"property-type":"color-ramp"},"heatmap-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},paint_symbol:{"icon-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-color":{type:"color",default:"#000000",transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",transition:!0,requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-halo-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"icon-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",requires:["icon-image"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"icon-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["icon-image","icon-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"text-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-color":{type:"color",default:"#000000",transition:!0,overridable:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-color":{type:"color",default:"rgba(0, 0, 0, 0)",transition:!0,requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-width":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-halo-blur":{type:"number",default:0,minimum:0,transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom","feature","feature-state"]},"property-type":"data-driven"},"text-translate":{type:"array",value:"number",length:2,default:[0,0],transition:!0,units:"pixels",requires:["text-field"],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"text-translate-anchor":{type:"enum",values:{map:{},viewport:{}},default:"map",requires:["text-field","text-translate"],expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"}},paint_raster:{"raster-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-hue-rotate":{type:"number",default:0,period:360,transition:!0,units:"degrees",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-brightness-min":{type:"number",default:0,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-brightness-max":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-saturation":{type:"number",default:0,minimum:-1,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-contrast":{type:"number",default:0,minimum:-1,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"raster-resampling":{type:"enum",values:{linear:{},nearest:{}},default:"linear",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"raster-fade-duration":{type:"number",default:300,minimum:0,transition:!1,units:"milliseconds",expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},paint_hillshade:{"hillshade-illumination-direction":{type:"number",default:335,minimum:0,maximum:359,transition:!1,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-illumination-anchor":{type:"enum",values:{map:{},viewport:{}},default:"viewport",expression:{interpolated:!1,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-exaggeration":{type:"number",default:.5,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-shadow-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-highlight-color":{type:"color",default:"#FFFFFF",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"hillshade-accent-color":{type:"color",default:"#000000",transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},paint_background:{"background-color":{type:"color",default:"#000000",transition:!0,requires:[{"!":"background-pattern"}],expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"},"background-pattern":{type:"resolvedImage",transition:!0,expression:{interpolated:!1,parameters:["zoom"]},"property-type":"cross-faded"},"background-opacity":{type:"number",default:1,minimum:0,maximum:1,transition:!0,expression:{interpolated:!0,parameters:["zoom"]},"property-type":"data-constant"}},transition:{duration:{type:"number",default:300,minimum:0,units:"milliseconds"},delay:{type:"number",default:0,minimum:0,units:"milliseconds"}},"property-type":{"data-driven":{type:"property-type"},"cross-faded":{type:"property-type"},"cross-faded-data-driven":{type:"property-type"},"color-ramp":{type:"property-type"},"data-constant":{type:"property-type"},constant:{type:"property-type"}},promoteId:{"*":{type:"string"}}},zt=function(t,e,r,n){this.message=(t?t+": ":"")+r,n&&(this.identifier=n),null!=e&&e.__line__&&(this.line=e.__line__);};function Ct(t){var e=t.value;return e?[new zt(t.key,e,"constants have been deprecated as of v8")]:[]}function Mt(t){for(var e=[],r=arguments.length-1;r-- >0;)e[r]=arguments[r+1];for(var n=0,i=e;n":"value"===t.itemType.kind?"array":"array<"+e+">"}return t.kind}var Zt=[Vt,Ft,Dt,Lt,Rt,qt,Ot,Kt(Ut),Nt];function Xt(t,e){if("error"===e.kind)return null;if("array"===t.kind){if("array"===e.kind&&(0===e.N&&"value"===e.itemType.kind||!Xt(t.itemType,e.itemType))&&("number"!=typeof t.N||t.N===e.N))return null}else {if(t.kind===e.kind)return null;if("value"===t.kind)for(var r=0,n=Zt;r255?255:t}function i(t){return n("%"===t[t.length-1]?parseFloat(t)/100*255:parseInt(t))}function a(t){return (e="%"===t[t.length-1]?parseFloat(t)/100:parseFloat(t))<0?0:e>1?1:e;var e;}function o(t,e,r){return r<0?r+=1:r>1&&(r-=1),6*r<1?t+(e-t)*r*6:2*r<1?e:3*r<2?t+(e-t)*(2/3-r)*6:t}try{e.parseCSSColor=function(t){var e,s=t.replace(/ /g,"").toLowerCase();if(s in r)return r[s].slice();if("#"===s[0])return 4===s.length?(e=parseInt(s.substr(1),16))>=0&&e<=4095?[(3840&e)>>4|(3840&e)>>8,240&e|(240&e)>>4,15&e|(15&e)<<4,1]:null:7===s.length&&(e=parseInt(s.substr(1),16))>=0&&e<=16777215?[(16711680&e)>>16,(65280&e)>>8,255&e,1]:null;var u=s.indexOf("("),l=s.indexOf(")");if(-1!==u&&l+1===s.length){var p=s.substr(0,u),c=s.substr(u+1,l-(u+1)).split(","),h=1;switch(p){case"rgba":if(4!==c.length)return null;h=a(c.pop());case"rgb":return 3!==c.length?null:[i(c[0]),i(c[1]),i(c[2]),h];case"hsla":if(4!==c.length)return null;h=a(c.pop());case"hsl":if(3!==c.length)return null;var f=(parseFloat(c[0])%360+360)%360/360,y=a(c[1]),d=a(c[2]),m=d<=.5?d*(y+1):d+y-d*y,v=2*d-m;return [n(255*o(v,m,f+1/3)),n(255*o(v,m,f)),n(255*o(v,m,f-1/3)),h];default:return null}}return null};}catch(t){}})).parseCSSColor,$t=function(t,e,r,n){void 0===n&&(n=1),this.r=t,this.g=e,this.b=r,this.a=n;};$t.parse=function(t){if(t){if(t instanceof $t)return t;if("string"==typeof t){var e=Yt(t);if(e)return new $t(e[0]/255*e[3],e[1]/255*e[3],e[2]/255*e[3],e[3])}}},$t.prototype.toString=function(){var t=this.toArray(),e=t[1],r=t[2],n=t[3];return "rgba("+Math.round(t[0])+","+Math.round(e)+","+Math.round(r)+","+n+")"},$t.prototype.toArray=function(){var t=this.a;return 0===t?[0,0,0,0]:[255*this.r/t,255*this.g/t,255*this.b/t,t]},$t.black=new $t(0,0,0,1),$t.white=new $t(1,1,1,1),$t.transparent=new $t(0,0,0,0),$t.red=new $t(1,0,0,1);var Wt=function(t,e,r){this.sensitivity=t?e?"variant":"case":e?"accent":"base",this.locale=r,this.collator=new Intl.Collator(this.locale?this.locale:[],{sensitivity:this.sensitivity,usage:"search"});};Wt.prototype.compare=function(t,e){return this.collator.compare(t,e)},Wt.prototype.resolvedLocale=function(){return new Intl.Collator(this.locale?this.locale:[]).resolvedOptions().locale};var Qt=function(t,e,r,n,i){this.text=t,this.image=e,this.scale=r,this.fontStack=n,this.textColor=i;},te=function(t){this.sections=t;};te.fromString=function(t){return new te([new Qt(t,null,null,null,null)])},te.prototype.isEmpty=function(){return 0===this.sections.length||!this.sections.some((function(t){return 0!==t.text.length||t.image&&0!==t.image.name.length}))},te.factory=function(t){return t instanceof te?t:te.fromString(t)},te.prototype.toString=function(){return 0===this.sections.length?"":this.sections.map((function(t){return t.text})).join("")},te.prototype.serialize=function(){for(var t=["format"],e=0,r=this.sections;e=0&&t<=255&&"number"==typeof e&&e>=0&&e<=255&&"number"==typeof r&&r>=0&&r<=255?void 0===n||"number"==typeof n&&n>=0&&n<=1?null:"Invalid rgba value ["+[t,e,r,n].join(", ")+"]: 'a' must be between 0 and 1.":"Invalid rgba value ["+("number"==typeof n?[t,e,r,n]:[t,e,r]).join(", ")+"]: 'r', 'g', and 'b' must be between 0 and 255."}function ne(t){if(null===t)return !0;if("string"==typeof t)return !0;if("boolean"==typeof t)return !0;if("number"==typeof t)return !0;if(t instanceof $t)return !0;if(t instanceof Wt)return !0;if(t instanceof te)return !0;if(t instanceof ee)return !0;if(Array.isArray(t)){for(var e=0,r=t;e2){var s=t[1];if("string"!=typeof s||!(s in ue)||"object"===s)return e.error('The item type argument of "array" must be one of string, number, boolean',1);a=ue[s],n++;}else a=Ut;if(t.length>3){if(null!==t[2]&&("number"!=typeof t[2]||t[2]<0||t[2]!==Math.floor(t[2])))return e.error('The length argument to "array" must be a positive integer literal',2);o=t[2],n++;}r=Kt(a,o);}else r=ue[i];for(var u=[];n1)&&e.push(n);}}return e.concat(this.args.map((function(t){return t.serialize()})))};var pe=function(t){this.type=qt,this.sections=t;};pe.parse=function(t,e){if(t.length<2)return e.error("Expected at least one argument.");var r=t[1];if(!Array.isArray(r)&&"object"==typeof r)return e.error("First argument must be an image or text section.");for(var n=[],i=!1,a=1;a<=t.length-1;++a){var o=t[a];if(i&&"object"==typeof o&&!Array.isArray(o)){i=!1;var s=null;if(o["font-scale"]&&!(s=e.parse(o["font-scale"],1,Ft)))return null;var u=null;if(o["text-font"]&&!(u=e.parse(o["text-font"],1,Kt(Dt))))return null;var l=null;if(o["text-color"]&&!(l=e.parse(o["text-color"],1,Rt)))return null;var p=n[n.length-1];p.scale=s,p.font=u,p.textColor=l;}else {var c=e.parse(t[a],1,Ut);if(!c)return null;var h=c.type.kind;if("string"!==h&&"value"!==h&&"null"!==h&&"resolvedImage"!==h)return e.error("Formatted text type must be 'string', 'value', 'image' or 'null'.");i=!0,n.push({content:c,scale:null,font:null,textColor:null});}}return new pe(n)},pe.prototype.evaluate=function(t){return new te(this.sections.map((function(e){var r=e.content.evaluate(t);return ie(r)===Nt?new Qt("",r,null,null,null):new Qt(ae(r),null,e.scale?e.scale.evaluate(t):null,e.font?e.font.evaluate(t).join(","):null,e.textColor?e.textColor.evaluate(t):null)})))},pe.prototype.eachChild=function(t){for(var e=0,r=this.sections;e-1),r},ce.prototype.eachChild=function(t){t(this.input);},ce.prototype.outputDefined=function(){return !1},ce.prototype.serialize=function(){return ["image",this.input.serialize()]};var he={"to-boolean":Lt,"to-color":Rt,"to-number":Ft,"to-string":Dt},fe=function(t,e){this.type=t,this.args=e;};fe.parse=function(t,e){if(t.length<2)return e.error("Expected at least one argument.");var r=t[0];if(("to-boolean"===r||"to-string"===r)&&2!==t.length)return e.error("Expected one argument.");for(var n=he[r],i=[],a=1;a4?"Invalid rbga value "+JSON.stringify(e)+": expected an array containing either three or four numeric values.":re(e[0],e[1],e[2],e[3])))return new $t(e[0]/255,e[1]/255,e[2]/255,e[3])}throw new se(r||"Could not parse color from value '"+("string"==typeof e?e:String(JSON.stringify(e)))+"'")}if("number"===this.type.kind){for(var o=null,s=0,u=this.args;s=e[2]||t[1]<=e[1]||t[3]>=e[3])}function be(t,e){var r=(180+t[0])/360,n=(180-180/Math.PI*Math.log(Math.tan(Math.PI/4+t[1]*Math.PI/360)))/360,i=Math.pow(2,e.z);return [Math.round(r*i*8192),Math.round(n*i*8192)]}function we(t,e,r){return e[1]>t[1]!=r[1]>t[1]&&t[0]<(r[0]-e[0])*(t[1]-e[1])/(r[1]-e[1])+e[0]}function _e(t,e){for(var r,n,i,a,o,s,u,l=!1,p=0,c=e.length;p0&&s<0||o<0&&s>0}function ke(t,e,r){for(var n=0,i=r;nr[2]){var i=.5*n,a=t[0]-r[0]>i?-n:r[0]-t[0]>i?n:0;0===a&&(a=t[0]-r[2]>i?-n:r[2]-t[0]>i?n:0),t[0]+=a;}ge(e,t);}function Te(t,e,r,n){for(var i=8192*Math.pow(2,n.z),a=[8192*n.x,8192*n.y],o=[],s=0,u=t;s=0)return !1;var r=!0;return t.eachChild((function(t){r&&!De(t,e)&&(r=!1);})),r}Be.parse=function(t,e){if(2!==t.length)return e.error("'within' expression requires exactly one argument, but found "+(t.length-1)+" instead.");if(ne(t[1])){var r=t[1];if("FeatureCollection"===r.type)for(var n=0;ne))throw new se("Input is not a number.");a=o-1;}return 0}Re.prototype.parse=function(t,e,r,n,i){return void 0===i&&(i={}),e?this.concat(e,r,n)._parse(t,i):this._parse(t,i)},Re.prototype._parse=function(t,e){function r(t,e,r){return "assert"===r?new le(e,[t]):"coerce"===r?new fe(e,[t]):t}if(null!==t&&"string"!=typeof t&&"boolean"!=typeof t&&"number"!=typeof t||(t=["literal",t]),Array.isArray(t)){if(0===t.length)return this.error('Expected an array with at least one element. If you wanted a literal array, use ["literal", []].');var n=t[0];if("string"!=typeof n)return this.error("Expression name must be a string, but found "+typeof n+' instead. If you wanted a literal array, use ["literal", [...]].',0),null;var i=this.registry[n];if(i){var a=i.parse(t,this);if(!a)return null;if(this.expectedType){var o=this.expectedType,s=a.type;if("string"!==o.kind&&"number"!==o.kind&&"boolean"!==o.kind&&"object"!==o.kind&&"array"!==o.kind||"value"!==s.kind)if("color"!==o.kind&&"formatted"!==o.kind&&"resolvedImage"!==o.kind||"value"!==s.kind&&"string"!==s.kind){if(this.checkSubtype(o,s))return null}else a=r(a,o,e.typeAnnotation||"coerce");else a=r(a,o,e.typeAnnotation||"assert");}if(!(a instanceof oe)&&"resolvedImage"!==a.type.kind&&function t(e){if(e instanceof Le)return t(e.boundExpression);if(e instanceof me&&"error"===e.name)return !1;if(e instanceof ve)return !1;if(e instanceof Be)return !1;var r=e instanceof fe||e instanceof le,n=!0;return e.eachChild((function(e){n=r?n&&t(e):n&&e instanceof oe;})),!!n&&Ve(e)&&De(e,["zoom","heatmap-density","line-progress","accumulated","is-supported-script"])}(a)){var u=new de;try{a=new oe(a.type,a.evaluate(u));}catch(t){return this.error(t.message),null}}return a}return this.error('Unknown expression "'+n+'". If you wanted a literal array, use ["literal", [...]].',0)}return this.error(void 0===t?"'undefined' value invalid. Use null instead.":"object"==typeof t?'Bare objects invalid. Use ["literal", {...}] instead.':"Expected an array, but found "+typeof t+" instead.")},Re.prototype.concat=function(t,e,r){var n="number"==typeof t?this.path.concat(t):this.path,i=r?this.scope.concat(r):this.scope;return new Re(this.registry,n,e||null,i,this.errors)},Re.prototype.error=function(t){for(var e=[],r=arguments.length-1;r-- >0;)e[r]=arguments[r+1];var n=""+this.key+e.map((function(t){return "["+t+"]"})).join("");this.errors.push(new Pt(n,t));},Re.prototype.checkSubtype=function(t,e){var r=Xt(t,e);return r&&this.error(r),r};var Ue=function(t,e,r){this.type=t,this.input=e,this.labels=[],this.outputs=[];for(var n=0,i=r;n=o)return e.error('Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.',u);var p=e.parse(s,l,i);if(!p)return null;i=i||p.type,n.push([o,p]);}return new Ue(i,r,n)},Ue.prototype.evaluate=function(t){var e=this.labels,r=this.outputs;if(1===e.length)return r[0].evaluate(t);var n=this.input.evaluate(t);if(n<=e[0])return r[0].evaluate(t);var i=e.length;return n>=e[i-1]?r[i-1].evaluate(t):r[Oe(e,n)].evaluate(t)},Ue.prototype.eachChild=function(t){t(this.input);for(var e=0,r=this.outputs;e0&&t.push(this.labels[e]),t.push(this.outputs[e].serialize());return t};var qe=Object.freeze({__proto__:null,number:je,color:function(t,e,r){return new $t(je(t.r,e.r,r),je(t.g,e.g,r),je(t.b,e.b,r),je(t.a,e.a,r))},array:function(t,e,r){return t.map((function(t,n){return je(t,e[n],r)}))}}),Ne=6/29*3*(6/29),Ke=Math.PI/180,Ge=180/Math.PI;function Ze(t){return t>.008856451679035631?Math.pow(t,1/3):t/Ne+4/29}function Xe(t){return t>6/29?t*t*t:Ne*(t-4/29)}function Je(t){return 255*(t<=.0031308?12.92*t:1.055*Math.pow(t,1/2.4)-.055)}function He(t){return (t/=255)<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function Ye(t){var e=He(t.r),r=He(t.g),n=He(t.b),i=Ze((.4124564*e+.3575761*r+.1804375*n)/.95047),a=Ze((.2126729*e+.7151522*r+.072175*n)/1);return {l:116*a-16,a:500*(i-a),b:200*(a-Ze((.0193339*e+.119192*r+.9503041*n)/1.08883)),alpha:t.a}}function $e(t){var e=(t.l+16)/116,r=isNaN(t.a)?e:e+t.a/500,n=isNaN(t.b)?e:e-t.b/200;return e=1*Xe(e),r=.95047*Xe(r),n=1.08883*Xe(n),new $t(Je(3.2404542*r-1.5371385*e-.4985314*n),Je(-.969266*r+1.8760108*e+.041556*n),Je(.0556434*r-.2040259*e+1.0572252*n),t.alpha)}function We(t,e,r){var n=e-t;return t+r*(n>180||n<-180?n-360*Math.round(n/360):n)}var Qe={forward:Ye,reverse:$e,interpolate:function(t,e,r){return {l:je(t.l,e.l,r),a:je(t.a,e.a,r),b:je(t.b,e.b,r),alpha:je(t.alpha,e.alpha,r)}}},tr={forward:function(t){var e=Ye(t),r=e.l,n=e.a,i=e.b,a=Math.atan2(i,n)*Ge;return {h:a<0?a+360:a,c:Math.sqrt(n*n+i*i),l:r,alpha:t.a}},reverse:function(t){var e=t.h*Ke,r=t.c;return $e({l:t.l,a:Math.cos(e)*r,b:Math.sin(e)*r,alpha:t.alpha})},interpolate:function(t,e,r){return {h:We(t.h,e.h,r),c:je(t.c,e.c,r),l:je(t.l,e.l,r),alpha:je(t.alpha,e.alpha,r)}}},er=Object.freeze({__proto__:null,lab:Qe,hcl:tr}),rr=function(t,e,r,n,i){this.type=t,this.operator=e,this.interpolation=r,this.input=n,this.labels=[],this.outputs=[];for(var a=0,o=i;a1})))return e.error("Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.",1);n={name:"cubic-bezier",controlPoints:s};}if(t.length-1<4)return e.error("Expected at least 4 arguments, but found only "+(t.length-1)+".");if((t.length-1)%2!=0)return e.error("Expected an even number of arguments.");if(!(i=e.parse(i,2,Ft)))return null;var u=[],l=null;"interpolate-hcl"===r||"interpolate-lab"===r?l=Rt:e.expectedType&&"value"!==e.expectedType.kind&&(l=e.expectedType);for(var p=0;p=c)return e.error('Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.',f);var d=e.parse(h,y,l);if(!d)return null;l=l||d.type,u.push([c,d]);}return "number"===l.kind||"color"===l.kind||"array"===l.kind&&"number"===l.itemType.kind&&"number"==typeof l.N?new rr(l,r,n,i,u):e.error("Type "+Gt(l)+" is not interpolatable.")},rr.prototype.evaluate=function(t){var e=this.labels,r=this.outputs;if(1===e.length)return r[0].evaluate(t);var n=this.input.evaluate(t);if(n<=e[0])return r[0].evaluate(t);var i=e.length;if(n>=e[i-1])return r[i-1].evaluate(t);var a=Oe(e,n),o=rr.interpolationFactor(this.interpolation,n,e[a],e[a+1]),s=r[a].evaluate(t),u=r[a+1].evaluate(t);return "interpolate"===this.operator?qe[this.type.kind.toLowerCase()](s,u,o):"interpolate-hcl"===this.operator?tr.reverse(tr.interpolate(tr.forward(s),tr.forward(u),o)):Qe.reverse(Qe.interpolate(Qe.forward(s),Qe.forward(u),o))},rr.prototype.eachChild=function(t){t(this.input);for(var e=0,r=this.outputs;e=r.length)throw new se("Array index out of bounds: "+e+" > "+(r.length-1)+".");if(e!==Math.floor(e))throw new se("Array index must be an integer, but found "+e+" instead.");return r[e]},or.prototype.eachChild=function(t){t(this.index),t(this.input);},or.prototype.outputDefined=function(){return !1},or.prototype.serialize=function(){return ["at",this.index.serialize(),this.input.serialize()]};var sr=function(t,e){this.type=Lt,this.needle=t,this.haystack=e;};sr.parse=function(t,e){if(3!==t.length)return e.error("Expected 2 arguments, but found "+(t.length-1)+" instead.");var r=e.parse(t[1],1,Ut),n=e.parse(t[2],2,Ut);return r&&n?Jt(r.type,[Lt,Dt,Ft,Vt,Ut])?new sr(r,n):e.error("Expected first argument to be of type boolean, string, number or null, but found "+Gt(r.type)+" instead"):null},sr.prototype.evaluate=function(t){var e=this.needle.evaluate(t),r=this.haystack.evaluate(t);if(!r)return !1;if(!Ht(e,["boolean","string","number","null"]))throw new se("Expected first argument to be of type boolean, string, number or null, but found "+Gt(ie(e))+" instead.");if(!Ht(r,["string","array"]))throw new se("Expected second argument to be of type array or string, but found "+Gt(ie(r))+" instead.");return r.indexOf(e)>=0},sr.prototype.eachChild=function(t){t(this.needle),t(this.haystack);},sr.prototype.outputDefined=function(){return !0},sr.prototype.serialize=function(){return ["in",this.needle.serialize(),this.haystack.serialize()]};var ur=function(t,e,r){this.type=Ft,this.needle=t,this.haystack=e,this.fromIndex=r;};ur.parse=function(t,e){if(t.length<=2||t.length>=5)return e.error("Expected 3 or 4 arguments, but found "+(t.length-1)+" instead.");var r=e.parse(t[1],1,Ut),n=e.parse(t[2],2,Ut);if(!r||!n)return null;if(!Jt(r.type,[Lt,Dt,Ft,Vt,Ut]))return e.error("Expected first argument to be of type boolean, string, number or null, but found "+Gt(r.type)+" instead");if(4===t.length){var i=e.parse(t[3],3,Ft);return i?new ur(r,n,i):null}return new ur(r,n)},ur.prototype.evaluate=function(t){var e=this.needle.evaluate(t),r=this.haystack.evaluate(t);if(!Ht(e,["boolean","string","number","null"]))throw new se("Expected first argument to be of type boolean, string, number or null, but found "+Gt(ie(e))+" instead.");if(!Ht(r,["string","array"]))throw new se("Expected second argument to be of type array or string, but found "+Gt(ie(r))+" instead.");if(this.fromIndex){var n=this.fromIndex.evaluate(t);return r.indexOf(e,n)}return r.indexOf(e)},ur.prototype.eachChild=function(t){t(this.needle),t(this.haystack),this.fromIndex&&t(this.fromIndex);},ur.prototype.outputDefined=function(){return !1},ur.prototype.serialize=function(){if(null!=this.fromIndex&&void 0!==this.fromIndex){var t=this.fromIndex.serialize();return ["index-of",this.needle.serialize(),this.haystack.serialize(),t]}return ["index-of",this.needle.serialize(),this.haystack.serialize()]};var lr=function(t,e,r,n,i,a){this.inputType=t,this.type=e,this.input=r,this.cases=n,this.outputs=i,this.otherwise=a;};lr.parse=function(t,e){if(t.length<5)return e.error("Expected at least 4 arguments, but found only "+(t.length-1)+".");if(t.length%2!=1)return e.error("Expected an even number of arguments.");var r,n;e.expectedType&&"value"!==e.expectedType.kind&&(n=e.expectedType);for(var i={},a=[],o=2;oNumber.MAX_SAFE_INTEGER)return l.error("Branch labels must be integers no larger than "+Number.MAX_SAFE_INTEGER+".");if("number"==typeof h&&Math.floor(h)!==h)return l.error("Numeric branch labels must be integer values.");if(r){if(l.checkSubtype(r,ie(h)))return null}else r=ie(h);if(void 0!==i[String(h)])return l.error("Branch labels must be unique.");i[String(h)]=a.length;}var f=e.parse(u,o,n);if(!f)return null;n=n||f.type,a.push(f);}var y=e.parse(t[1],1,Ut);if(!y)return null;var d=e.parse(t[t.length-1],t.length-1,n);return d?"value"!==y.type.kind&&e.concat(1).checkSubtype(r,y.type)?null:new lr(r,n,y,i,a,d):null},lr.prototype.evaluate=function(t){var e=this.input.evaluate(t);return (ie(e)===this.inputType&&this.outputs[this.cases[e]]||this.otherwise).evaluate(t)},lr.prototype.eachChild=function(t){t(this.input),this.outputs.forEach(t),t(this.otherwise);},lr.prototype.outputDefined=function(){return this.outputs.every((function(t){return t.outputDefined()}))&&this.otherwise.outputDefined()},lr.prototype.serialize=function(){for(var t=this,e=["match",this.input.serialize()],r=[],n={},i=0,a=Object.keys(this.cases).sort();i=5)return e.error("Expected 3 or 4 arguments, but found "+(t.length-1)+" instead.");var r=e.parse(t[1],1,Ut),n=e.parse(t[2],2,Ft);if(!r||!n)return null;if(!Jt(r.type,[Kt(Ut),Dt,Ut]))return e.error("Expected first argument to be of type array or string, but found "+Gt(r.type)+" instead");if(4===t.length){var i=e.parse(t[3],3,Ft);return i?new cr(r.type,r,n,i):null}return new cr(r.type,r,n)},cr.prototype.evaluate=function(t){var e=this.input.evaluate(t),r=this.beginIndex.evaluate(t);if(!Ht(e,["string","array"]))throw new se("Expected first argument to be of type array or string, but found "+Gt(ie(e))+" instead.");if(this.endIndex){var n=this.endIndex.evaluate(t);return e.slice(r,n)}return e.slice(r)},cr.prototype.eachChild=function(t){t(this.input),t(this.beginIndex),this.endIndex&&t(this.endIndex);},cr.prototype.outputDefined=function(){return !1},cr.prototype.serialize=function(){if(null!=this.endIndex&&void 0!==this.endIndex){var t=this.endIndex.serialize();return ["slice",this.input.serialize(),this.beginIndex.serialize(),t]}return ["slice",this.input.serialize(),this.beginIndex.serialize()]};var dr=yr("==",(function(t,e,r){return e===r}),fr),mr=yr("!=",(function(t,e,r){return e!==r}),(function(t,e,r,n){return !fr(0,e,r,n)})),vr=yr("<",(function(t,e,r){return e",(function(t,e,r){return e>r}),(function(t,e,r,n){return n.compare(e,r)>0})),xr=yr("<=",(function(t,e,r){return e<=r}),(function(t,e,r,n){return n.compare(e,r)<=0})),br=yr(">=",(function(t,e,r){return e>=r}),(function(t,e,r,n){return n.compare(e,r)>=0})),wr=function(t,e,r,n,i){this.type=Dt,this.number=t,this.locale=e,this.currency=r,this.minFractionDigits=n,this.maxFractionDigits=i;};wr.parse=function(t,e){if(3!==t.length)return e.error("Expected two arguments.");var r=e.parse(t[1],1,Ft);if(!r)return null;var n=t[2];if("object"!=typeof n||Array.isArray(n))return e.error("NumberFormat options argument must be an object.");var i=null;if(n.locale&&!(i=e.parse(n.locale,1,Dt)))return null;var a=null;if(n.currency&&!(a=e.parse(n.currency,1,Dt)))return null;var o=null;if(n["min-fraction-digits"]&&!(o=e.parse(n["min-fraction-digits"],1,Ft)))return null;var s=null;return n["max-fraction-digits"]&&!(s=e.parse(n["max-fraction-digits"],1,Ft))?null:new wr(r,i,a,o,s)},wr.prototype.evaluate=function(t){return new Intl.NumberFormat(this.locale?this.locale.evaluate(t):[],{style:this.currency?"currency":"decimal",currency:this.currency?this.currency.evaluate(t):void 0,minimumFractionDigits:this.minFractionDigits?this.minFractionDigits.evaluate(t):void 0,maximumFractionDigits:this.maxFractionDigits?this.maxFractionDigits.evaluate(t):void 0}).format(this.number.evaluate(t))},wr.prototype.eachChild=function(t){t(this.number),this.locale&&t(this.locale),this.currency&&t(this.currency),this.minFractionDigits&&t(this.minFractionDigits),this.maxFractionDigits&&t(this.maxFractionDigits);},wr.prototype.outputDefined=function(){return !1},wr.prototype.serialize=function(){var t={};return this.locale&&(t.locale=this.locale.serialize()),this.currency&&(t.currency=this.currency.serialize()),this.minFractionDigits&&(t["min-fraction-digits"]=this.minFractionDigits.serialize()),this.maxFractionDigits&&(t["max-fraction-digits"]=this.maxFractionDigits.serialize()),["number-format",this.number.serialize(),t]};var _r=function(t){this.type=Ft,this.input=t;};_r.parse=function(t,e){if(2!==t.length)return e.error("Expected 1 argument, but found "+(t.length-1)+" instead.");var r=e.parse(t[1],1);return r?"array"!==r.type.kind&&"string"!==r.type.kind&&"value"!==r.type.kind?e.error("Expected argument of type string or array, but found "+Gt(r.type)+" instead."):new _r(r):null},_r.prototype.evaluate=function(t){var e=this.input.evaluate(t);if("string"==typeof e)return e.length;if(Array.isArray(e))return e.length;throw new se("Expected value to be of type string or array, but found "+Gt(ie(e))+" instead.")},_r.prototype.eachChild=function(t){t(this.input);},_r.prototype.outputDefined=function(){return !1},_r.prototype.serialize=function(){var t=["length"];return this.eachChild((function(e){t.push(e.serialize());})),t};var Ar={"==":dr,"!=":mr,">":gr,"<":vr,">=":br,"<=":xr,array:le,at:or,boolean:le,case:pr,coalesce:ir,collator:ve,format:pe,image:ce,in:sr,"index-of":ur,interpolate:rr,"interpolate-hcl":rr,"interpolate-lab":rr,length:_r,let:ar,literal:oe,match:lr,number:le,"number-format":wr,object:le,slice:cr,step:Ue,string:le,"to-boolean":fe,"to-color":fe,"to-number":fe,"to-string":fe,var:Le,within:Be};function Sr(t,e){var r=e[0],n=e[1],i=e[2],a=e[3];r=r.evaluate(t),n=n.evaluate(t),i=i.evaluate(t);var o=a?a.evaluate(t):1,s=re(r,n,i,o);if(s)throw new se(s);return new $t(r/255*o,n/255*o,i/255*o,o)}function kr(t,e){return t in e}function Ir(t,e){var r=e[t];return void 0===r?null:r}function zr(t){return {type:t}}function Cr(t){return {result:"success",value:t}}function Mr(t){return {result:"error",value:t}}function Er(t){return "data-driven"===t["property-type"]||"cross-faded-data-driven"===t["property-type"]}function Tr(t){return !!t.expression&&t.expression.parameters.indexOf("zoom")>-1}function Pr(t){return !!t.expression&&t.expression.interpolated}function Br(t){return t instanceof Number?"number":t instanceof String?"string":t instanceof Boolean?"boolean":Array.isArray(t)?"array":null===t?"null":typeof t}function Vr(t){return "object"==typeof t&&null!==t&&!Array.isArray(t)}function Fr(t){return t}function Dr(t,e,r){return void 0!==t?t:void 0!==e?e:void 0!==r?r:void 0}function Lr(t,e,r,n,i){return Dr(typeof r===i?n[r]:void 0,t.default,e.default)}function Rr(t,e,r){if("number"!==Br(r))return Dr(t.default,e.default);var n=t.stops.length;if(1===n)return t.stops[0][1];if(r<=t.stops[0][0])return t.stops[0][1];if(r>=t.stops[n-1][0])return t.stops[n-1][1];var i=Oe(t.stops.map((function(t){return t[0]})),r);return t.stops[i][1]}function Or(t,e,r){var n=void 0!==t.base?t.base:1;if("number"!==Br(r))return Dr(t.default,e.default);var i=t.stops.length;if(1===i)return t.stops[0][1];if(r<=t.stops[0][0])return t.stops[0][1];if(r>=t.stops[i-1][0])return t.stops[i-1][1];var a=Oe(t.stops.map((function(t){return t[0]})),r),o=function(t,e,r,n){var i=n-r,a=t-r;return 0===i?0:1===e?a/i:(Math.pow(e,a)-1)/(Math.pow(e,i)-1)}(r,n,t.stops[a][0],t.stops[a+1][0]),s=t.stops[a][1],u=t.stops[a+1][1],l=qe[e.type]||Fr;if(t.colorSpace&&"rgb"!==t.colorSpace){var p=er[t.colorSpace];l=function(t,e){return p.reverse(p.interpolate(p.forward(t),p.forward(e),o))};}return "function"==typeof s.evaluate?{evaluate:function(){for(var t=[],e=arguments.length;e--;)t[e]=arguments[e];var r=s.evaluate.apply(void 0,t),n=u.evaluate.apply(void 0,t);if(void 0!==r&&void 0!==n)return l(r,n,o)}}:l(s,u,o)}function Ur(t,e,r){return "color"===e.type?r=$t.parse(r):"formatted"===e.type?r=te.fromString(r.toString()):"resolvedImage"===e.type?r=ee.fromString(r.toString()):Br(r)===e.type||"enum"===e.type&&e.values[r]||(r=void 0),Dr(r,t.default,e.default)}me.register(Ar,{error:[{kind:"error"},[Dt],function(t,e){throw new se(e[0].evaluate(t))}],typeof:[Dt,[Ut],function(t,e){return Gt(ie(e[0].evaluate(t)))}],"to-rgba":[Kt(Ft,4),[Rt],function(t,e){return e[0].evaluate(t).toArray()}],rgb:[Rt,[Ft,Ft,Ft],Sr],rgba:[Rt,[Ft,Ft,Ft,Ft],Sr],has:{type:Lt,overloads:[[[Dt],function(t,e){return kr(e[0].evaluate(t),t.properties())}],[[Dt,Ot],function(t,e){var r=e[1];return kr(e[0].evaluate(t),r.evaluate(t))}]]},get:{type:Ut,overloads:[[[Dt],function(t,e){return Ir(e[0].evaluate(t),t.properties())}],[[Dt,Ot],function(t,e){var r=e[1];return Ir(e[0].evaluate(t),r.evaluate(t))}]]},"feature-state":[Ut,[Dt],function(t,e){return Ir(e[0].evaluate(t),t.featureState||{})}],properties:[Ot,[],function(t){return t.properties()}],"geometry-type":[Dt,[],function(t){return t.geometryType()}],id:[Ut,[],function(t){return t.id()}],zoom:[Ft,[],function(t){return t.globals.zoom}],"heatmap-density":[Ft,[],function(t){return t.globals.heatmapDensity||0}],"line-progress":[Ft,[],function(t){return t.globals.lineProgress||0}],accumulated:[Ut,[],function(t){return void 0===t.globals.accumulated?null:t.globals.accumulated}],"+":[Ft,zr(Ft),function(t,e){for(var r=0,n=0,i=e;n":[Lt,[Dt,Ut],function(t,e){var r=e[0],n=e[1],i=t.properties()[r.value],a=n.value;return typeof i==typeof a&&i>a}],"filter-id->":[Lt,[Ut],function(t,e){var r=e[0],n=t.id(),i=r.value;return typeof n==typeof i&&n>i}],"filter-<=":[Lt,[Dt,Ut],function(t,e){var r=e[0],n=e[1],i=t.properties()[r.value],a=n.value;return typeof i==typeof a&&i<=a}],"filter-id-<=":[Lt,[Ut],function(t,e){var r=e[0],n=t.id(),i=r.value;return typeof n==typeof i&&n<=i}],"filter->=":[Lt,[Dt,Ut],function(t,e){var r=e[0],n=e[1],i=t.properties()[r.value],a=n.value;return typeof i==typeof a&&i>=a}],"filter-id->=":[Lt,[Ut],function(t,e){var r=e[0],n=t.id(),i=r.value;return typeof n==typeof i&&n>=i}],"filter-has":[Lt,[Ut],function(t,e){return e[0].value in t.properties()}],"filter-has-id":[Lt,[],function(t){return null!==t.id()&&void 0!==t.id()}],"filter-type-in":[Lt,[Kt(Dt)],function(t,e){return e[0].value.indexOf(t.geometryType())>=0}],"filter-id-in":[Lt,[Kt(Ut)],function(t,e){return e[0].value.indexOf(t.id())>=0}],"filter-in-small":[Lt,[Dt,Kt(Ut)],function(t,e){var r=e[0];return e[1].value.indexOf(t.properties()[r.value])>=0}],"filter-in-large":[Lt,[Dt,Kt(Ut)],function(t,e){var r=e[0],n=e[1];return function(t,e,r,n){for(;r<=n;){var i=r+n>>1;if(e[i]===t)return !0;e[i]>t?n=i-1:r=i+1;}return !1}(t.properties()[r.value],n.value,0,n.value.length-1)}],all:{type:Lt,overloads:[[[Lt,Lt],function(t,e){var r=e[1];return e[0].evaluate(t)&&r.evaluate(t)}],[zr(Lt),function(t,e){for(var r=0,n=e;r0&&"string"==typeof t[0]&&t[0]in Ar}function Nr(t,e){var r=new Re(Ar,[],e?function(t){var e={color:Rt,string:Dt,number:Ft,enum:Dt,boolean:Lt,formatted:qt,resolvedImage:Nt};return "array"===t.type?Kt(e[t.value]||Ut,t.length):e[t.type]}(e):void 0),n=r.parse(t,void 0,void 0,void 0,e&&"string"===e.type?{typeAnnotation:"coerce"}:void 0);return n?Cr(new jr(n,e)):Mr(r.errors)}jr.prototype.evaluateWithoutErrorHandling=function(t,e,r,n,i,a){return this._evaluator.globals=t,this._evaluator.feature=e,this._evaluator.featureState=r,this._evaluator.canonical=n,this._evaluator.availableImages=i||null,this._evaluator.formattedSection=a,this.expression.evaluate(this._evaluator)},jr.prototype.evaluate=function(t,e,r,n,i,a){this._evaluator.globals=t,this._evaluator.feature=e||null,this._evaluator.featureState=r||null,this._evaluator.canonical=n,this._evaluator.availableImages=i||null,this._evaluator.formattedSection=a||null;try{var o=this.expression.evaluate(this._evaluator);if(null==o||"number"==typeof o&&o!=o)return this._defaultValue;if(this._enumValues&&!(o in this._enumValues))throw new se("Expected value to be one of "+Object.keys(this._enumValues).map((function(t){return JSON.stringify(t)})).join(", ")+", but found "+JSON.stringify(o)+" instead.");return o}catch(t){return this._warningHistory[t.message]||(this._warningHistory[t.message]=!0,"undefined"!=typeof console&&console.warn(t.message)),this._defaultValue}};var Kr=function(t,e){this.kind=t,this._styleExpression=e,this.isStateDependent="constant"!==t&&!Fe(e.expression);};Kr.prototype.evaluateWithoutErrorHandling=function(t,e,r,n,i,a){return this._styleExpression.evaluateWithoutErrorHandling(t,e,r,n,i,a)},Kr.prototype.evaluate=function(t,e,r,n,i,a){return this._styleExpression.evaluate(t,e,r,n,i,a)};var Gr=function(t,e,r,n){this.kind=t,this.zoomStops=r,this._styleExpression=e,this.isStateDependent="camera"!==t&&!Fe(e.expression),this.interpolationType=n;};function Zr(t,e){if("error"===(t=Nr(t,e)).result)return t;var r=t.value.expression,n=Ve(r);if(!n&&!Er(e))return Mr([new Pt("","data expressions not supported")]);var i=De(r,["zoom"]);if(!i&&!Tr(e))return Mr([new Pt("","zoom expressions not supported")]);var a=function t(e){var r=null;if(e instanceof ar)r=t(e.result);else if(e instanceof ir)for(var n=0,i=e.args;nn.maximum?[new zt(e,r,r+" is greater than the maximum value "+n.maximum)]:[]}function $r(t){var e,r,n,i=t.valueSpec,a=Et(t.value.type),o={},s="categorical"!==a&&void 0===t.value.property,u=!s,l="array"===Br(t.value.stops)&&"array"===Br(t.value.stops[0])&&"object"===Br(t.value.stops[0][0]),p=Jr({key:t.key,value:t.value,valueSpec:t.styleSpec.function,style:t.style,styleSpec:t.styleSpec,objectElementValidators:{stops:function(t){if("identity"===a)return [new zt(t.key,t.value,'identity function may not have a "stops" property')];var e=[],r=t.value;return e=e.concat(Hr({key:t.key,value:r,valueSpec:t.valueSpec,style:t.style,styleSpec:t.styleSpec,arrayElementValidator:c})),"array"===Br(r)&&0===r.length&&e.push(new zt(t.key,r,"array must have at least one stop")),e},default:function(t){return bn({key:t.key,value:t.value,valueSpec:i,style:t.style,styleSpec:t.styleSpec})}}});return "identity"===a&&s&&p.push(new zt(t.key,t.value,'missing required property "property"')),"identity"===a||t.value.stops||p.push(new zt(t.key,t.value,'missing required property "stops"')),"exponential"===a&&t.valueSpec.expression&&!Pr(t.valueSpec)&&p.push(new zt(t.key,t.value,"exponential functions not supported")),t.styleSpec.$version>=8&&(u&&!Er(t.valueSpec)?p.push(new zt(t.key,t.value,"property functions not supported")):s&&!Tr(t.valueSpec)&&p.push(new zt(t.key,t.value,"zoom functions not supported"))),"categorical"!==a&&!l||void 0!==t.value.property||p.push(new zt(t.key,t.value,'"property" property is required')),p;function c(t){var e=[],a=t.value,s=t.key;if("array"!==Br(a))return [new zt(s,a,"array expected, "+Br(a)+" found")];if(2!==a.length)return [new zt(s,a,"array length 2 expected, length "+a.length+" found")];if(l){if("object"!==Br(a[0]))return [new zt(s,a,"object expected, "+Br(a[0])+" found")];if(void 0===a[0].zoom)return [new zt(s,a,"object stop key must have zoom")];if(void 0===a[0].value)return [new zt(s,a,"object stop key must have value")];if(n&&n>Et(a[0].zoom))return [new zt(s,a[0].zoom,"stop zoom values must appear in ascending order")];Et(a[0].zoom)!==n&&(n=Et(a[0].zoom),r=void 0,o={}),e=e.concat(Jr({key:s+"[0]",value:a[0],valueSpec:{zoom:{}},style:t.style,styleSpec:t.styleSpec,objectElementValidators:{zoom:Yr,value:h}}));}else e=e.concat(h({key:s+"[0]",value:a[0],valueSpec:{},style:t.style,styleSpec:t.styleSpec},a));return qr(Tt(a[1]))?e.concat([new zt(s+"[1]",a[1],"expressions are not allowed in function stops.")]):e.concat(bn({key:s+"[1]",value:a[1],valueSpec:i,style:t.style,styleSpec:t.styleSpec}))}function h(t,n){var s=Br(t.value),u=Et(t.value),l=null!==t.value?t.value:n;if(e){if(s!==e)return [new zt(t.key,l,s+" stop domain type must match previous stop domain type "+e)]}else e=s;if("number"!==s&&"string"!==s&&"boolean"!==s)return [new zt(t.key,l,"stop domain value must be a number, string, or boolean")];if("number"!==s&&"categorical"!==a){var p="number expected, "+s+" found";return Er(i)&&void 0===a&&(p+='\nIf you intended to use a categorical function, specify `"type": "categorical"`.'),[new zt(t.key,l,p)]}return "categorical"!==a||"number"!==s||isFinite(u)&&Math.floor(u)===u?"categorical"!==a&&"number"===s&&void 0!==r&&u=2&&"$id"!==t[1]&&"$type"!==t[1];case"in":return t.length>=3&&("string"!=typeof t[1]||Array.isArray(t[2]));case"!in":case"!has":case"none":return !1;case"==":case"!=":case">":case">=":case"<":case"<=":return 3!==t.length||Array.isArray(t[1])||Array.isArray(t[2]);case"any":case"all":for(var e=0,r=t.slice(1);ee?1:0}function an(t){if(!t)return !0;var e,r=t[0];return t.length<=1?"any"!==r:"=="===r?on(t[1],t[2],"=="):"!="===r?ln(on(t[1],t[2],"==")):"<"===r||">"===r||"<="===r||">="===r?on(t[1],t[2],r):"any"===r?(e=t.slice(1),["any"].concat(e.map(an))):"all"===r?["all"].concat(t.slice(1).map(an)):"none"===r?["all"].concat(t.slice(1).map(an).map(ln)):"in"===r?sn(t[1],t.slice(2)):"!in"===r?ln(sn(t[1],t.slice(2))):"has"===r?un(t[1]):"!has"===r?ln(un(t[1])):"within"!==r||t}function on(t,e,r){switch(t){case"$type":return ["filter-type-"+r,e];case"$id":return ["filter-id-"+r,e];default:return ["filter-"+r,t,e]}}function sn(t,e){if(0===e.length)return !1;switch(t){case"$type":return ["filter-type-in",["literal",e]];case"$id":return ["filter-id-in",["literal",e]];default:return e.length>200&&!e.some((function(t){return typeof t!=typeof e[0]}))?["filter-in-large",t,["literal",e.sort(nn)]]:["filter-in-small",t,["literal",e]]}}function un(t){switch(t){case"$type":return !0;case"$id":return ["filter-has-id"];default:return ["filter-has",t]}}function ln(t){return ["!",t]}function pn(t){return tn(Tt(t.value))?Wr(Mt({},t,{expressionContext:"filter",valueSpec:{value:"boolean"}})):function t(e){var r=e.value,n=e.key;if("array"!==Br(r))return [new zt(n,r,"array expected, "+Br(r)+" found")];var i,a=e.styleSpec,o=[];if(r.length<1)return [new zt(n,r,"filter array must have at least 1 element")];switch(o=o.concat(Qr({key:n+"[0]",value:r[0],valueSpec:a.filter_operator,style:e.style,styleSpec:e.styleSpec})),Et(r[0])){case"<":case"<=":case">":case">=":r.length>=2&&"$type"===Et(r[1])&&o.push(new zt(n,r,'"$type" cannot be use with operator "'+r[0]+'"'));case"==":case"!=":3!==r.length&&o.push(new zt(n,r,'filter array for operator "'+r[0]+'" must have 3 elements'));case"in":case"!in":r.length>=2&&"string"!==(i=Br(r[1]))&&o.push(new zt(n+"[1]",r[1],"string expected, "+i+" found"));for(var s=2;s=p[f+0]&&n>=p[f+1])?(o[h]=!0,a.push(l[h])):o[h]=!1;}}},Tn.prototype._forEachCell=function(t,e,r,n,i,a,o,s){for(var u=this._convertToCellCoord(t),l=this._convertToCellCoord(e),p=this._convertToCellCoord(r),c=this._convertToCellCoord(n),h=u;h<=p;h++)for(var f=l;f<=c;f++){var y=this.d*f+h;if((!s||s(this._convertFromCellCoord(h),this._convertFromCellCoord(f),this._convertFromCellCoord(h+1),this._convertFromCellCoord(f+1)))&&i.call(this,t,e,r,n,y,a,o,s))return}},Tn.prototype._convertFromCellCoord=function(t){return (t-this.padding)/this.scale},Tn.prototype._convertToCellCoord=function(t){return Math.max(0,Math.min(this.d-1,Math.floor(t*this.scale)+this.padding))},Tn.prototype.toArrayBuffer=function(){if(this.arrayBuffer)return this.arrayBuffer;for(var t=this.cells,e=3+this.cells.length+1+1,r=0,n=0;n=0)){var p=t[l];u[l]=Vn[s].shallow.indexOf(l)>=0?p:On(p,e);}t instanceof Error&&(u.message=t.message);}if(u.$name)throw new Error("$name property is reserved for worker serialization logic.");return "Object"!==s&&(u.$name=s),u}throw new Error("can't serialize object of type "+typeof t)}function Un(t){if(null==t||"boolean"==typeof t||"number"==typeof t||"string"==typeof t||t instanceof Boolean||t instanceof Number||t instanceof String||t instanceof Date||t instanceof RegExp||Ln(t)||Rn(t)||ArrayBuffer.isView(t)||t instanceof Pn)return t;if(Array.isArray(t))return t.map(Un);if("object"==typeof t){var e=t.$name||"Object",r=Vn[e].klass;if(!r)throw new Error("can't deserialize unregistered class "+e);if(r.deserialize)return r.deserialize(t);for(var n=Object.create(r.prototype),i=0,a=Object.keys(t);i=0?s:Un(s);}}return n}throw new Error("can't deserialize object of type "+typeof t)}var jn=function(){this.first=!0;};jn.prototype.update=function(t,e){var r=Math.floor(t);return this.first?(this.first=!1,this.lastIntegerZoom=r,this.lastIntegerZoomTime=0,this.lastZoom=t,this.lastFloorZoom=r,!0):(this.lastFloorZoom>r?(this.lastIntegerZoom=r+1,this.lastIntegerZoomTime=e):this.lastFloorZoom=128&&t<=255},Arabic:function(t){return t>=1536&&t<=1791},"Arabic Supplement":function(t){return t>=1872&&t<=1919},"Arabic Extended-A":function(t){return t>=2208&&t<=2303},"Hangul Jamo":function(t){return t>=4352&&t<=4607},"Unified Canadian Aboriginal Syllabics":function(t){return t>=5120&&t<=5759},Khmer:function(t){return t>=6016&&t<=6143},"Unified Canadian Aboriginal Syllabics Extended":function(t){return t>=6320&&t<=6399},"General Punctuation":function(t){return t>=8192&&t<=8303},"Letterlike Symbols":function(t){return t>=8448&&t<=8527},"Number Forms":function(t){return t>=8528&&t<=8591},"Miscellaneous Technical":function(t){return t>=8960&&t<=9215},"Control Pictures":function(t){return t>=9216&&t<=9279},"Optical Character Recognition":function(t){return t>=9280&&t<=9311},"Enclosed Alphanumerics":function(t){return t>=9312&&t<=9471},"Geometric Shapes":function(t){return t>=9632&&t<=9727},"Miscellaneous Symbols":function(t){return t>=9728&&t<=9983},"Miscellaneous Symbols and Arrows":function(t){return t>=11008&&t<=11263},"CJK Radicals Supplement":function(t){return t>=11904&&t<=12031},"Kangxi Radicals":function(t){return t>=12032&&t<=12255},"Ideographic Description Characters":function(t){return t>=12272&&t<=12287},"CJK Symbols and Punctuation":function(t){return t>=12288&&t<=12351},Hiragana:function(t){return t>=12352&&t<=12447},Katakana:function(t){return t>=12448&&t<=12543},Bopomofo:function(t){return t>=12544&&t<=12591},"Hangul Compatibility Jamo":function(t){return t>=12592&&t<=12687},Kanbun:function(t){return t>=12688&&t<=12703},"Bopomofo Extended":function(t){return t>=12704&&t<=12735},"CJK Strokes":function(t){return t>=12736&&t<=12783},"Katakana Phonetic Extensions":function(t){return t>=12784&&t<=12799},"Enclosed CJK Letters and Months":function(t){return t>=12800&&t<=13055},"CJK Compatibility":function(t){return t>=13056&&t<=13311},"CJK Unified Ideographs Extension A":function(t){return t>=13312&&t<=19903},"Yijing Hexagram Symbols":function(t){return t>=19904&&t<=19967},"CJK Unified Ideographs":function(t){return t>=19968&&t<=40959},"Yi Syllables":function(t){return t>=40960&&t<=42127},"Yi Radicals":function(t){return t>=42128&&t<=42191},"Hangul Jamo Extended-A":function(t){return t>=43360&&t<=43391},"Hangul Syllables":function(t){return t>=44032&&t<=55215},"Hangul Jamo Extended-B":function(t){return t>=55216&&t<=55295},"Private Use Area":function(t){return t>=57344&&t<=63743},"CJK Compatibility Ideographs":function(t){return t>=63744&&t<=64255},"Arabic Presentation Forms-A":function(t){return t>=64336&&t<=65023},"Vertical Forms":function(t){return t>=65040&&t<=65055},"CJK Compatibility Forms":function(t){return t>=65072&&t<=65103},"Small Form Variants":function(t){return t>=65104&&t<=65135},"Arabic Presentation Forms-B":function(t){return t>=65136&&t<=65279},"Halfwidth and Fullwidth Forms":function(t){return t>=65280&&t<=65519}};function Nn(t){for(var e=0,r=t;e=65097&&t<=65103)||qn["CJK Compatibility Ideographs"](t)||qn["CJK Compatibility"](t)||qn["CJK Radicals Supplement"](t)||qn["CJK Strokes"](t)||!(!qn["CJK Symbols and Punctuation"](t)||t>=12296&&t<=12305||t>=12308&&t<=12319||12336===t)||qn["CJK Unified Ideographs Extension A"](t)||qn["CJK Unified Ideographs"](t)||qn["Enclosed CJK Letters and Months"](t)||qn["Hangul Compatibility Jamo"](t)||qn["Hangul Jamo Extended-A"](t)||qn["Hangul Jamo Extended-B"](t)||qn["Hangul Jamo"](t)||qn["Hangul Syllables"](t)||qn.Hiragana(t)||qn["Ideographic Description Characters"](t)||qn.Kanbun(t)||qn["Kangxi Radicals"](t)||qn["Katakana Phonetic Extensions"](t)||qn.Katakana(t)&&12540!==t||!(!qn["Halfwidth and Fullwidth Forms"](t)||65288===t||65289===t||65293===t||t>=65306&&t<=65310||65339===t||65341===t||65343===t||t>=65371&&t<=65503||65507===t||t>=65512&&t<=65519)||!(!qn["Small Form Variants"](t)||t>=65112&&t<=65118||t>=65123&&t<=65126)||qn["Unified Canadian Aboriginal Syllabics"](t)||qn["Unified Canadian Aboriginal Syllabics Extended"](t)||qn["Vertical Forms"](t)||qn["Yijing Hexagram Symbols"](t)||qn["Yi Syllables"](t)||qn["Yi Radicals"](t))))}function Gn(t){return !(Kn(t)||function(t){return !!(qn["Latin-1 Supplement"](t)&&(167===t||169===t||174===t||177===t||188===t||189===t||190===t||215===t||247===t)||qn["General Punctuation"](t)&&(8214===t||8224===t||8225===t||8240===t||8241===t||8251===t||8252===t||8258===t||8263===t||8264===t||8265===t||8273===t)||qn["Letterlike Symbols"](t)||qn["Number Forms"](t)||qn["Miscellaneous Technical"](t)&&(t>=8960&&t<=8967||t>=8972&&t<=8991||t>=8996&&t<=9e3||9003===t||t>=9085&&t<=9114||t>=9150&&t<=9165||9167===t||t>=9169&&t<=9179||t>=9186&&t<=9215)||qn["Control Pictures"](t)&&9251!==t||qn["Optical Character Recognition"](t)||qn["Enclosed Alphanumerics"](t)||qn["Geometric Shapes"](t)||qn["Miscellaneous Symbols"](t)&&!(t>=9754&&t<=9759)||qn["Miscellaneous Symbols and Arrows"](t)&&(t>=11026&&t<=11055||t>=11088&&t<=11097||t>=11192&&t<=11243)||qn["CJK Symbols and Punctuation"](t)||qn.Katakana(t)||qn["Private Use Area"](t)||qn["CJK Compatibility Forms"](t)||qn["Small Form Variants"](t)||qn["Halfwidth and Fullwidth Forms"](t)||8734===t||8756===t||8757===t||t>=9984&&t<=10087||t>=10102&&t<=10131||65532===t||65533===t)}(t))}function Zn(t){return t>=1424&&t<=2303||qn["Arabic Presentation Forms-A"](t)||qn["Arabic Presentation Forms-B"](t)}function Xn(t,e){return !(!e&&Zn(t)||t>=2304&&t<=3583||t>=3840&&t<=4255||qn.Khmer(t))}function Jn(t){for(var e=0,r=t;e-1&&(Yn="error"),Hn&&Hn(t);};function Qn(){ti.fire(new At("pluginStateChange",{pluginStatus:Yn,pluginURL:$n}));}var ti=new kt,ei=function(){return Yn},ri=function(){if("deferred"!==Yn||!$n)throw new Error("rtl-text-plugin cannot be downloaded unless a pluginURL is specified");Yn="loading",Qn(),$n&>({url:$n},(function(t){t?Wn(t):(Yn="loaded",Qn());}));},ni={applyArabicShaping:null,processBidirectionalText:null,processStyledBidirectionalText:null,isLoaded:function(){return "loaded"===Yn||null!=ni.applyArabicShaping},isLoading:function(){return "loading"===Yn},setState:function(t){Yn=t.pluginStatus,$n=t.pluginURL;},isParsed:function(){return null!=ni.applyArabicShaping&&null!=ni.processBidirectionalText&&null!=ni.processStyledBidirectionalText},getPluginURL:function(){return $n}},ii=function(t,e){this.zoom=t,e?(this.now=e.now,this.fadeDuration=e.fadeDuration,this.zoomHistory=e.zoomHistory,this.transition=e.transition):(this.now=0,this.fadeDuration=0,this.zoomHistory=new jn,this.transition={});};ii.prototype.isSupportedScript=function(t){return function(t,e){for(var r=0,n=t;rthis.zoomHistory.lastIntegerZoom?{fromScale:2,toScale:1,t:e+(1-e)*r}:{fromScale:.5,toScale:1,t:1-(1-r)*e}};var ai=function(t,e){this.property=t,this.value=e,this.expression=function(t,e){if(Vr(t))return new Xr(t,e);if(qr(t)){var r=Zr(t,e);if("error"===r.result)throw new Error(r.value.map((function(t){return t.key+": "+t.message})).join(", "));return r.value}var n=t;return "string"==typeof t&&"color"===e.type&&(n=$t.parse(t)),{kind:"constant",evaluate:function(){return n}}}(void 0===e?t.specification.default:e,t.specification);};ai.prototype.isDataDriven=function(){return "source"===this.expression.kind||"composite"===this.expression.kind},ai.prototype.possiblyEvaluate=function(t,e,r){return this.property.possiblyEvaluate(this,t,e,r)};var oi=function(t){this.property=t,this.value=new ai(t,void 0);};oi.prototype.transitioned=function(t,e){return new ui(this.property,this.value,e,p({},t.transition,this.transition),t.now)},oi.prototype.untransitioned=function(){return new ui(this.property,this.value,null,{},0)};var si=function(t){this._properties=t,this._values=Object.create(t.defaultTransitionablePropertyValues);};si.prototype.getValue=function(t){return x(this._values[t].value.value)},si.prototype.setValue=function(t,e){this._values.hasOwnProperty(t)||(this._values[t]=new oi(this._values[t].property)),this._values[t].value=new ai(this._values[t].property,null===e?void 0:x(e));},si.prototype.getTransition=function(t){return x(this._values[t].transition)},si.prototype.setTransition=function(t,e){this._values.hasOwnProperty(t)||(this._values[t]=new oi(this._values[t].property)),this._values[t].transition=x(e)||void 0;},si.prototype.serialize=function(){for(var t={},e=0,r=Object.keys(this._values);ethis.end)return this.prior=null,i;if(this.value.isDataDriven())return this.prior=null,i;if(n=1)return 1;var e=t*t,r=e*t;return 4*(t<.5?r:3*(t-e)+r-.75)}(o))}return i};var li=function(t){this._properties=t,this._values=Object.create(t.defaultTransitioningPropertyValues);};li.prototype.possiblyEvaluate=function(t,e,r){for(var n=new hi(this._properties),i=0,a=Object.keys(this._values);in.zoomHistory.lastIntegerZoom?{from:t,to:e}:{from:r,to:e}},e.prototype.interpolate=function(t){return t},e}(yi),mi=function(t){this.specification=t;};mi.prototype.possiblyEvaluate=function(t,e,r,n){if(void 0!==t.value){if("constant"===t.expression.kind){var i=t.expression.evaluate(e,null,{},r,n);return this._calculate(i,i,i,e)}return this._calculate(t.expression.evaluate(new ii(Math.floor(e.zoom-1),e)),t.expression.evaluate(new ii(Math.floor(e.zoom),e)),t.expression.evaluate(new ii(Math.floor(e.zoom+1),e)),e)}},mi.prototype._calculate=function(t,e,r,n){return n.zoom>n.zoomHistory.lastIntegerZoom?{from:t,to:e}:{from:r,to:e}},mi.prototype.interpolate=function(t){return t};var vi=function(t){this.specification=t;};vi.prototype.possiblyEvaluate=function(t,e,r,n){return !!t.expression.evaluate(e,null,{},r,n)},vi.prototype.interpolate=function(){return !1};var gi=function(t){for(var e in this.properties=t,this.defaultPropertyValues={},this.defaultTransitionablePropertyValues={},this.defaultTransitioningPropertyValues={},this.defaultPossiblyEvaluatedValues={},this.overridableProperties=[],t){var r=t[e];r.specification.overridable&&this.overridableProperties.push(e);var n=this.defaultPropertyValues[e]=new ai(r,void 0),i=this.defaultTransitionablePropertyValues[e]=new oi(r);this.defaultTransitioningPropertyValues[e]=i.untransitioned(),this.defaultPossiblyEvaluatedValues[e]=n.possiblyEvaluate({});}};Fn("DataDrivenProperty",yi),Fn("DataConstantProperty",fi),Fn("CrossFadedDataDrivenProperty",di),Fn("CrossFadedProperty",mi),Fn("ColorRampProperty",vi);var xi=function(t){function e(e,r){if(t.call(this),this.id=e.id,this.type=e.type,this._featureFilter={filter:function(){return !0},needGeometry:!1},"custom"!==e.type&&(this.metadata=(e=e).metadata,this.minzoom=e.minzoom,this.maxzoom=e.maxzoom,"background"!==e.type&&(this.source=e.source,this.sourceLayer=e["source-layer"],this.filter=e.filter),r.layout&&(this._unevaluatedLayout=new pi(r.layout)),r.paint)){for(var n in this._transitionablePaint=new si(r.paint),e.paint)this.setPaintProperty(n,e.paint[n],{validate:!1});for(var i in e.layout)this.setLayoutProperty(i,e.layout[i],{validate:!1});this._transitioningPaint=this._transitionablePaint.untransitioned(),this.paint=new hi(r.paint);}}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getCrossfadeParameters=function(){return this._crossfadeParameters},e.prototype.getLayoutProperty=function(t){return "visibility"===t?this.visibility:this._unevaluatedLayout.getValue(t)},e.prototype.setLayoutProperty=function(t,e,r){void 0===r&&(r={}),null!=e&&this._validate(Cn,"layers."+this.id+".layout."+t,t,e,r)||("visibility"!==t?this._unevaluatedLayout.setValue(t,e):this.visibility=e);},e.prototype.getPaintProperty=function(t){return m(t,"-transition")?this._transitionablePaint.getTransition(t.slice(0,-"-transition".length)):this._transitionablePaint.getValue(t)},e.prototype.setPaintProperty=function(t,e,r){if(void 0===r&&(r={}),null!=e&&this._validate(zn,"layers."+this.id+".paint."+t,t,e,r))return !1;if(m(t,"-transition"))return this._transitionablePaint.setTransition(t.slice(0,-"-transition".length),e||void 0),!1;var n=this._transitionablePaint._values[t],i="cross-faded-data-driven"===n.property.specification["property-type"],a=n.value.isDataDriven(),o=n.value;this._transitionablePaint.setValue(t,e),this._handleSpecialPaintPropertyUpdate(t);var s=this._transitionablePaint._values[t].value;return s.isDataDriven()||a||i||this._handleOverridablePaintPropertyUpdate(t,o,s)},e.prototype._handleSpecialPaintPropertyUpdate=function(t){},e.prototype._handleOverridablePaintPropertyUpdate=function(t,e,r){return !1},e.prototype.isHidden=function(t){return !!(this.minzoom&&t=this.maxzoom)||"none"===this.visibility},e.prototype.updateTransitions=function(t){this._transitioningPaint=this._transitionablePaint.transitioned(t,this._transitioningPaint);},e.prototype.hasTransition=function(){return this._transitioningPaint.hasTransition()},e.prototype.recalculate=function(t,e){t.getCrossfadeParameters&&(this._crossfadeParameters=t.getCrossfadeParameters()),this._unevaluatedLayout&&(this.layout=this._unevaluatedLayout.possiblyEvaluate(t,void 0,e)),this.paint=this._transitioningPaint.possiblyEvaluate(t,void 0,e);},e.prototype.serialize=function(){var t={id:this.id,type:this.type,source:this.source,"source-layer":this.sourceLayer,metadata:this.metadata,minzoom:this.minzoom,maxzoom:this.maxzoom,filter:this.filter,layout:this._unevaluatedLayout&&this._unevaluatedLayout.serialize(),paint:this._transitionablePaint&&this._transitionablePaint.serialize()};return this.visibility&&(t.layout=t.layout||{},t.layout.visibility=this.visibility),g(t,(function(t,e){return !(void 0===t||"layout"===e&&!Object.keys(t).length||"paint"===e&&!Object.keys(t).length)}))},e.prototype._validate=function(t,e,r,n,i){return void 0===i&&(i={}),(!i||!1!==i.validate)&&Mn(this,t.call(kn,{key:e,layerType:this.type,objectKey:r,value:n,styleSpec:It,style:{glyphs:!0,sprite:!0}}))},e.prototype.is3D=function(){return !1},e.prototype.isTileClipped=function(){return !1},e.prototype.hasOffscreenPass=function(){return !1},e.prototype.resize=function(){},e.prototype.isStateDependent=function(){for(var t in this.paint._values){var e=this.paint.get(t);if(e instanceof ci&&Er(e.property.specification)&&("source"===e.value.kind||"composite"===e.value.kind)&&e.value.isStateDependent)return !0}return !1},e}(kt),bi={Int8:Int8Array,Uint8:Uint8Array,Int16:Int16Array,Uint16:Uint16Array,Int32:Int32Array,Uint32:Uint32Array,Float32:Float32Array},wi=function(t,e){this._structArray=t,this._pos1=e*this.size,this._pos2=this._pos1/2,this._pos4=this._pos1/4,this._pos8=this._pos1/8;},_i=function(){this.isTransferred=!1,this.capacity=-1,this.resize(0);};function Ai(t,e){void 0===e&&(e=1);var r=0,n=0;return {members:t.map((function(t){var i=bi[t.type].BYTES_PER_ELEMENT,a=r=Si(r,Math.max(e,i)),o=t.components||1;return n=Math.max(n,i),r+=i*o,{name:t.name,type:t.type,components:o,offset:a}})),size:Si(r,Math.max(n,e)),alignment:e}}function Si(t,e){return Math.ceil(t/e)*e}_i.serialize=function(t,e){return t._trim(),e&&(t.isTransferred=!0,e.push(t.arrayBuffer)),{length:t.length,arrayBuffer:t.arrayBuffer}},_i.deserialize=function(t){var e=Object.create(this.prototype);return e.arrayBuffer=t.arrayBuffer,e.length=t.length,e.capacity=t.arrayBuffer.byteLength/e.bytesPerElement,e._refreshViews(),e},_i.prototype._trim=function(){this.length!==this.capacity&&(this.capacity=this.length,this.arrayBuffer=this.arrayBuffer.slice(0,this.length*this.bytesPerElement),this._refreshViews());},_i.prototype.clear=function(){this.length=0;},_i.prototype.resize=function(t){this.reserve(t),this.length=t;},_i.prototype.reserve=function(t){if(t>this.capacity){this.capacity=Math.max(t,Math.floor(5*this.capacity),128),this.arrayBuffer=new ArrayBuffer(this.capacity*this.bytesPerElement);var e=this.uint8;this._refreshViews(),e&&this.uint8.set(e);}},_i.prototype._refreshViews=function(){throw new Error("_refreshViews() must be implemented by each concrete StructArray layout")};var ki=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e){var r=this.length;return this.resize(r+1),this.emplace(r,t,e)},e.prototype.emplace=function(t,e,r){var n=2*t;return this.int16[n+0]=e,this.int16[n+1]=r,t},e}(_i);ki.prototype.bytesPerElement=4,Fn("StructArrayLayout2i4",ki);var Ii=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n){var i=this.length;return this.resize(i+1),this.emplace(i,t,e,r,n)},e.prototype.emplace=function(t,e,r,n,i){var a=4*t;return this.int16[a+0]=e,this.int16[a+1]=r,this.int16[a+2]=n,this.int16[a+3]=i,t},e}(_i);Ii.prototype.bytesPerElement=8,Fn("StructArrayLayout4i8",Ii);var zi=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n,i,a){var o=this.length;return this.resize(o+1),this.emplace(o,t,e,r,n,i,a)},e.prototype.emplace=function(t,e,r,n,i,a,o){var s=6*t;return this.int16[s+0]=e,this.int16[s+1]=r,this.int16[s+2]=n,this.int16[s+3]=i,this.int16[s+4]=a,this.int16[s+5]=o,t},e}(_i);zi.prototype.bytesPerElement=12,Fn("StructArrayLayout2i4i12",zi);var Ci=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n,i,a){var o=this.length;return this.resize(o+1),this.emplace(o,t,e,r,n,i,a)},e.prototype.emplace=function(t,e,r,n,i,a,o){var s=4*t,u=8*t;return this.int16[s+0]=e,this.int16[s+1]=r,this.uint8[u+4]=n,this.uint8[u+5]=i,this.uint8[u+6]=a,this.uint8[u+7]=o,t},e}(_i);Ci.prototype.bytesPerElement=8,Fn("StructArrayLayout2i4ub8",Ci);var Mi=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n,i,a,o,s,u,l){var p=this.length;return this.resize(p+1),this.emplace(p,t,e,r,n,i,a,o,s,u,l)},e.prototype.emplace=function(t,e,r,n,i,a,o,s,u,l,p){var c=9*t,h=18*t;return this.uint16[c+0]=e,this.uint16[c+1]=r,this.uint16[c+2]=n,this.uint16[c+3]=i,this.uint16[c+4]=a,this.uint16[c+5]=o,this.uint16[c+6]=s,this.uint16[c+7]=u,this.uint8[h+16]=l,this.uint8[h+17]=p,t},e}(_i);Mi.prototype.bytesPerElement=18,Fn("StructArrayLayout8ui2ub18",Mi);var Ei=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n,i,a,o,s,u,l,p,c){var h=this.length;return this.resize(h+1),this.emplace(h,t,e,r,n,i,a,o,s,u,l,p,c)},e.prototype.emplace=function(t,e,r,n,i,a,o,s,u,l,p,c,h){var f=12*t;return this.int16[f+0]=e,this.int16[f+1]=r,this.int16[f+2]=n,this.int16[f+3]=i,this.uint16[f+4]=a,this.uint16[f+5]=o,this.uint16[f+6]=s,this.uint16[f+7]=u,this.int16[f+8]=l,this.int16[f+9]=p,this.int16[f+10]=c,this.int16[f+11]=h,t},e}(_i);Ei.prototype.bytesPerElement=24,Fn("StructArrayLayout4i4ui4i24",Ei);var Ti=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r){var n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)},e.prototype.emplace=function(t,e,r,n){var i=3*t;return this.float32[i+0]=e,this.float32[i+1]=r,this.float32[i+2]=n,t},e}(_i);Ti.prototype.bytesPerElement=12,Fn("StructArrayLayout3f12",Ti);var Pi=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t){var e=this.length;return this.resize(e+1),this.emplace(e,t)},e.prototype.emplace=function(t,e){return this.uint32[1*t+0]=e,t},e}(_i);Pi.prototype.bytesPerElement=4,Fn("StructArrayLayout1ul4",Pi);var Bi=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n,i,a,o,s,u){var l=this.length;return this.resize(l+1),this.emplace(l,t,e,r,n,i,a,o,s,u)},e.prototype.emplace=function(t,e,r,n,i,a,o,s,u,l){var p=10*t,c=5*t;return this.int16[p+0]=e,this.int16[p+1]=r,this.int16[p+2]=n,this.int16[p+3]=i,this.int16[p+4]=a,this.int16[p+5]=o,this.uint32[c+3]=s,this.uint16[p+8]=u,this.uint16[p+9]=l,t},e}(_i);Bi.prototype.bytesPerElement=20,Fn("StructArrayLayout6i1ul2ui20",Bi);var Vi=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n,i,a){var o=this.length;return this.resize(o+1),this.emplace(o,t,e,r,n,i,a)},e.prototype.emplace=function(t,e,r,n,i,a,o){var s=6*t;return this.int16[s+0]=e,this.int16[s+1]=r,this.int16[s+2]=n,this.int16[s+3]=i,this.int16[s+4]=a,this.int16[s+5]=o,t},e}(_i);Vi.prototype.bytesPerElement=12,Fn("StructArrayLayout2i2i2i12",Vi);var Fi=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n,i){var a=this.length;return this.resize(a+1),this.emplace(a,t,e,r,n,i)},e.prototype.emplace=function(t,e,r,n,i,a){var o=4*t,s=8*t;return this.float32[o+0]=e,this.float32[o+1]=r,this.float32[o+2]=n,this.int16[s+6]=i,this.int16[s+7]=a,t},e}(_i);Fi.prototype.bytesPerElement=16,Fn("StructArrayLayout2f1f2i16",Fi);var Di=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n){var i=this.length;return this.resize(i+1),this.emplace(i,t,e,r,n)},e.prototype.emplace=function(t,e,r,n,i){var a=12*t,o=3*t;return this.uint8[a+0]=e,this.uint8[a+1]=r,this.float32[o+1]=n,this.float32[o+2]=i,t},e}(_i);Di.prototype.bytesPerElement=12,Fn("StructArrayLayout2ub2f12",Di);var Li=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r){var n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)},e.prototype.emplace=function(t,e,r,n){var i=3*t;return this.uint16[i+0]=e,this.uint16[i+1]=r,this.uint16[i+2]=n,t},e}(_i);Li.prototype.bytesPerElement=6,Fn("StructArrayLayout3ui6",Li);var Ri=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n,i,a,o,s,u,l,p,c,h,f,y,d,m){var v=this.length;return this.resize(v+1),this.emplace(v,t,e,r,n,i,a,o,s,u,l,p,c,h,f,y,d,m)},e.prototype.emplace=function(t,e,r,n,i,a,o,s,u,l,p,c,h,f,y,d,m,v){var g=24*t,x=12*t,b=48*t;return this.int16[g+0]=e,this.int16[g+1]=r,this.uint16[g+2]=n,this.uint16[g+3]=i,this.uint32[x+2]=a,this.uint32[x+3]=o,this.uint32[x+4]=s,this.uint16[g+10]=u,this.uint16[g+11]=l,this.uint16[g+12]=p,this.float32[x+7]=c,this.float32[x+8]=h,this.uint8[b+36]=f,this.uint8[b+37]=y,this.uint8[b+38]=d,this.uint32[x+10]=m,this.int16[g+22]=v,t},e}(_i);Ri.prototype.bytesPerElement=48,Fn("StructArrayLayout2i2ui3ul3ui2f3ub1ul1i48",Ri);var Oi=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n,i,a,o,s,u,l,p,c,h,f,y,d,m,v,g,x,b,w,_,A,S,k,I,z){var C=this.length;return this.resize(C+1),this.emplace(C,t,e,r,n,i,a,o,s,u,l,p,c,h,f,y,d,m,v,g,x,b,w,_,A,S,k,I,z)},e.prototype.emplace=function(t,e,r,n,i,a,o,s,u,l,p,c,h,f,y,d,m,v,g,x,b,w,_,A,S,k,I,z,C){var M=34*t,E=17*t;return this.int16[M+0]=e,this.int16[M+1]=r,this.int16[M+2]=n,this.int16[M+3]=i,this.int16[M+4]=a,this.int16[M+5]=o,this.int16[M+6]=s,this.int16[M+7]=u,this.uint16[M+8]=l,this.uint16[M+9]=p,this.uint16[M+10]=c,this.uint16[M+11]=h,this.uint16[M+12]=f,this.uint16[M+13]=y,this.uint16[M+14]=d,this.uint16[M+15]=m,this.uint16[M+16]=v,this.uint16[M+17]=g,this.uint16[M+18]=x,this.uint16[M+19]=b,this.uint16[M+20]=w,this.uint16[M+21]=_,this.uint16[M+22]=A,this.uint32[E+12]=S,this.float32[E+13]=k,this.float32[E+14]=I,this.float32[E+15]=z,this.float32[E+16]=C,t},e}(_i);Oi.prototype.bytesPerElement=68,Fn("StructArrayLayout8i15ui1ul4f68",Oi);var Ui=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t){var e=this.length;return this.resize(e+1),this.emplace(e,t)},e.prototype.emplace=function(t,e){return this.float32[1*t+0]=e,t},e}(_i);Ui.prototype.bytesPerElement=4,Fn("StructArrayLayout1f4",Ui);var ji=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r){var n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)},e.prototype.emplace=function(t,e,r,n){var i=3*t;return this.int16[i+0]=e,this.int16[i+1]=r,this.int16[i+2]=n,t},e}(_i);ji.prototype.bytesPerElement=6,Fn("StructArrayLayout3i6",ji);var qi=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r){var n=this.length;return this.resize(n+1),this.emplace(n,t,e,r)},e.prototype.emplace=function(t,e,r,n){var i=4*t;return this.uint32[2*t+0]=e,this.uint16[i+2]=r,this.uint16[i+3]=n,t},e}(_i);qi.prototype.bytesPerElement=8,Fn("StructArrayLayout1ul2ui8",qi);var Ni=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e){var r=this.length;return this.resize(r+1),this.emplace(r,t,e)},e.prototype.emplace=function(t,e,r){var n=2*t;return this.uint16[n+0]=e,this.uint16[n+1]=r,t},e}(_i);Ni.prototype.bytesPerElement=4,Fn("StructArrayLayout2ui4",Ni);var Ki=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t){var e=this.length;return this.resize(e+1),this.emplace(e,t)},e.prototype.emplace=function(t,e){return this.uint16[1*t+0]=e,t},e}(_i);Ki.prototype.bytesPerElement=2,Fn("StructArrayLayout1ui2",Ki);var Gi=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e){var r=this.length;return this.resize(r+1),this.emplace(r,t,e)},e.prototype.emplace=function(t,e,r){var n=2*t;return this.float32[n+0]=e,this.float32[n+1]=r,t},e}(_i);Gi.prototype.bytesPerElement=8,Fn("StructArrayLayout2f8",Gi);var Zi=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._refreshViews=function(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer);},e.prototype.emplaceBack=function(t,e,r,n){var i=this.length;return this.resize(i+1),this.emplace(i,t,e,r,n)},e.prototype.emplace=function(t,e,r,n,i){var a=4*t;return this.float32[a+0]=e,this.float32[a+1]=r,this.float32[a+2]=n,this.float32[a+3]=i,t},e}(_i);Zi.prototype.bytesPerElement=16,Fn("StructArrayLayout4f16",Zi);var Xi=function(t){function e(){t.apply(this,arguments);}t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e;var r={anchorPointX:{configurable:!0},anchorPointY:{configurable:!0},x1:{configurable:!0},y1:{configurable:!0},x2:{configurable:!0},y2:{configurable:!0},featureIndex:{configurable:!0},sourceLayerIndex:{configurable:!0},bucketIndex:{configurable:!0},anchorPoint:{configurable:!0}};return r.anchorPointX.get=function(){return this._structArray.int16[this._pos2+0]},r.anchorPointY.get=function(){return this._structArray.int16[this._pos2+1]},r.x1.get=function(){return this._structArray.int16[this._pos2+2]},r.y1.get=function(){return this._structArray.int16[this._pos2+3]},r.x2.get=function(){return this._structArray.int16[this._pos2+4]},r.y2.get=function(){return this._structArray.int16[this._pos2+5]},r.featureIndex.get=function(){return this._structArray.uint32[this._pos4+3]},r.sourceLayerIndex.get=function(){return this._structArray.uint16[this._pos2+8]},r.bucketIndex.get=function(){return this._structArray.uint16[this._pos2+9]},r.anchorPoint.get=function(){return new i(this.anchorPointX,this.anchorPointY)},Object.defineProperties(e.prototype,r),e}(wi);Xi.prototype.size=20;var Ji=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.get=function(t){return new Xi(this,t)},e}(Bi);Fn("CollisionBoxArray",Ji);var Hi=function(t){function e(){t.apply(this,arguments);}t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e;var r={anchorX:{configurable:!0},anchorY:{configurable:!0},glyphStartIndex:{configurable:!0},numGlyphs:{configurable:!0},vertexStartIndex:{configurable:!0},lineStartIndex:{configurable:!0},lineLength:{configurable:!0},segment:{configurable:!0},lowerSize:{configurable:!0},upperSize:{configurable:!0},lineOffsetX:{configurable:!0},lineOffsetY:{configurable:!0},writingMode:{configurable:!0},placedOrientation:{configurable:!0},hidden:{configurable:!0},crossTileID:{configurable:!0},associatedIconIndex:{configurable:!0}};return r.anchorX.get=function(){return this._structArray.int16[this._pos2+0]},r.anchorY.get=function(){return this._structArray.int16[this._pos2+1]},r.glyphStartIndex.get=function(){return this._structArray.uint16[this._pos2+2]},r.numGlyphs.get=function(){return this._structArray.uint16[this._pos2+3]},r.vertexStartIndex.get=function(){return this._structArray.uint32[this._pos4+2]},r.lineStartIndex.get=function(){return this._structArray.uint32[this._pos4+3]},r.lineLength.get=function(){return this._structArray.uint32[this._pos4+4]},r.segment.get=function(){return this._structArray.uint16[this._pos2+10]},r.lowerSize.get=function(){return this._structArray.uint16[this._pos2+11]},r.upperSize.get=function(){return this._structArray.uint16[this._pos2+12]},r.lineOffsetX.get=function(){return this._structArray.float32[this._pos4+7]},r.lineOffsetY.get=function(){return this._structArray.float32[this._pos4+8]},r.writingMode.get=function(){return this._structArray.uint8[this._pos1+36]},r.placedOrientation.get=function(){return this._structArray.uint8[this._pos1+37]},r.placedOrientation.set=function(t){this._structArray.uint8[this._pos1+37]=t;},r.hidden.get=function(){return this._structArray.uint8[this._pos1+38]},r.hidden.set=function(t){this._structArray.uint8[this._pos1+38]=t;},r.crossTileID.get=function(){return this._structArray.uint32[this._pos4+10]},r.crossTileID.set=function(t){this._structArray.uint32[this._pos4+10]=t;},r.associatedIconIndex.get=function(){return this._structArray.int16[this._pos2+22]},Object.defineProperties(e.prototype,r),e}(wi);Hi.prototype.size=48;var Yi=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.get=function(t){return new Hi(this,t)},e}(Ri);Fn("PlacedSymbolArray",Yi);var $i=function(t){function e(){t.apply(this,arguments);}t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e;var r={anchorX:{configurable:!0},anchorY:{configurable:!0},rightJustifiedTextSymbolIndex:{configurable:!0},centerJustifiedTextSymbolIndex:{configurable:!0},leftJustifiedTextSymbolIndex:{configurable:!0},verticalPlacedTextSymbolIndex:{configurable:!0},placedIconSymbolIndex:{configurable:!0},verticalPlacedIconSymbolIndex:{configurable:!0},key:{configurable:!0},textBoxStartIndex:{configurable:!0},textBoxEndIndex:{configurable:!0},verticalTextBoxStartIndex:{configurable:!0},verticalTextBoxEndIndex:{configurable:!0},iconBoxStartIndex:{configurable:!0},iconBoxEndIndex:{configurable:!0},verticalIconBoxStartIndex:{configurable:!0},verticalIconBoxEndIndex:{configurable:!0},featureIndex:{configurable:!0},numHorizontalGlyphVertices:{configurable:!0},numVerticalGlyphVertices:{configurable:!0},numIconVertices:{configurable:!0},numVerticalIconVertices:{configurable:!0},useRuntimeCollisionCircles:{configurable:!0},crossTileID:{configurable:!0},textBoxScale:{configurable:!0},textOffset0:{configurable:!0},textOffset1:{configurable:!0},collisionCircleDiameter:{configurable:!0}};return r.anchorX.get=function(){return this._structArray.int16[this._pos2+0]},r.anchorY.get=function(){return this._structArray.int16[this._pos2+1]},r.rightJustifiedTextSymbolIndex.get=function(){return this._structArray.int16[this._pos2+2]},r.centerJustifiedTextSymbolIndex.get=function(){return this._structArray.int16[this._pos2+3]},r.leftJustifiedTextSymbolIndex.get=function(){return this._structArray.int16[this._pos2+4]},r.verticalPlacedTextSymbolIndex.get=function(){return this._structArray.int16[this._pos2+5]},r.placedIconSymbolIndex.get=function(){return this._structArray.int16[this._pos2+6]},r.verticalPlacedIconSymbolIndex.get=function(){return this._structArray.int16[this._pos2+7]},r.key.get=function(){return this._structArray.uint16[this._pos2+8]},r.textBoxStartIndex.get=function(){return this._structArray.uint16[this._pos2+9]},r.textBoxEndIndex.get=function(){return this._structArray.uint16[this._pos2+10]},r.verticalTextBoxStartIndex.get=function(){return this._structArray.uint16[this._pos2+11]},r.verticalTextBoxEndIndex.get=function(){return this._structArray.uint16[this._pos2+12]},r.iconBoxStartIndex.get=function(){return this._structArray.uint16[this._pos2+13]},r.iconBoxEndIndex.get=function(){return this._structArray.uint16[this._pos2+14]},r.verticalIconBoxStartIndex.get=function(){return this._structArray.uint16[this._pos2+15]},r.verticalIconBoxEndIndex.get=function(){return this._structArray.uint16[this._pos2+16]},r.featureIndex.get=function(){return this._structArray.uint16[this._pos2+17]},r.numHorizontalGlyphVertices.get=function(){return this._structArray.uint16[this._pos2+18]},r.numVerticalGlyphVertices.get=function(){return this._structArray.uint16[this._pos2+19]},r.numIconVertices.get=function(){return this._structArray.uint16[this._pos2+20]},r.numVerticalIconVertices.get=function(){return this._structArray.uint16[this._pos2+21]},r.useRuntimeCollisionCircles.get=function(){return this._structArray.uint16[this._pos2+22]},r.crossTileID.get=function(){return this._structArray.uint32[this._pos4+12]},r.crossTileID.set=function(t){this._structArray.uint32[this._pos4+12]=t;},r.textBoxScale.get=function(){return this._structArray.float32[this._pos4+13]},r.textOffset0.get=function(){return this._structArray.float32[this._pos4+14]},r.textOffset1.get=function(){return this._structArray.float32[this._pos4+15]},r.collisionCircleDiameter.get=function(){return this._structArray.float32[this._pos4+16]},Object.defineProperties(e.prototype,r),e}(wi);$i.prototype.size=68;var Wi=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.get=function(t){return new $i(this,t)},e}(Oi);Fn("SymbolInstanceArray",Wi);var Qi=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getoffsetX=function(t){return this.float32[1*t+0]},e}(Ui);Fn("GlyphOffsetArray",Qi);var ta=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.getx=function(t){return this.int16[3*t+0]},e.prototype.gety=function(t){return this.int16[3*t+1]},e.prototype.gettileUnitDistanceFromAnchor=function(t){return this.int16[3*t+2]},e}(ji);Fn("SymbolLineVertexArray",ta);var ea=function(t){function e(){t.apply(this,arguments);}t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e;var r={featureIndex:{configurable:!0},sourceLayerIndex:{configurable:!0},bucketIndex:{configurable:!0}};return r.featureIndex.get=function(){return this._structArray.uint32[this._pos4+0]},r.sourceLayerIndex.get=function(){return this._structArray.uint16[this._pos2+2]},r.bucketIndex.get=function(){return this._structArray.uint16[this._pos2+3]},Object.defineProperties(e.prototype,r),e}(wi);ea.prototype.size=8;var ra=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.get=function(t){return new ea(this,t)},e}(qi);Fn("FeatureIndexArray",ra);var na=Ai([{name:"a_pos",components:2,type:"Int16"}],4).members,ia=function(t){void 0===t&&(t=[]),this.segments=t;};function aa(t,e){return 256*(t=u(Math.floor(t),0,255))+u(Math.floor(e),0,255)}ia.prototype.prepareSegment=function(t,e,r,n){var i=this.segments[this.segments.length-1];return t>ia.MAX_VERTEX_ARRAY_LENGTH&&w("Max vertices per segment is "+ia.MAX_VERTEX_ARRAY_LENGTH+": bucket requested "+t),(!i||i.vertexLength+t>ia.MAX_VERTEX_ARRAY_LENGTH||i.sortKey!==n)&&(i={vertexOffset:e.length,primitiveOffset:r.length,vertexLength:0,primitiveLength:0},void 0!==n&&(i.sortKey=n),this.segments.push(i)),i},ia.prototype.get=function(){return this.segments},ia.prototype.destroy=function(){for(var t=0,e=this.segments;t>>16)*o&65535)<<16)&4294967295)<<15|u>>>17))*s+(((u>>>16)*s&65535)<<16)&4294967295)<<13|i>>>19))+((5*(i>>>16)&65535)<<16)&4294967295))+((58964+(a>>>16)&65535)<<16);switch(u=0,r){case 3:u^=(255&t.charCodeAt(l+2))<<16;case 2:u^=(255&t.charCodeAt(l+1))<<8;case 1:i^=u=(65535&(u=(u=(65535&(u^=255&t.charCodeAt(l)))*o+(((u>>>16)*o&65535)<<16)&4294967295)<<15|u>>>17))*s+(((u>>>16)*s&65535)<<16)&4294967295;}return i^=t.length,i=2246822507*(65535&(i^=i>>>16))+((2246822507*(i>>>16)&65535)<<16)&4294967295,i=3266489909*(65535&(i^=i>>>13))+((3266489909*(i>>>16)&65535)<<16)&4294967295,(i^=i>>>16)>>>0};})),ua=e((function(t){t.exports=function(t,e){for(var r,n=t.length,i=e^n,a=0;n>=4;)r=1540483477*(65535&(r=255&t.charCodeAt(a)|(255&t.charCodeAt(++a))<<8|(255&t.charCodeAt(++a))<<16|(255&t.charCodeAt(++a))<<24))+((1540483477*(r>>>16)&65535)<<16),i=1540483477*(65535&i)+((1540483477*(i>>>16)&65535)<<16)^(r=1540483477*(65535&(r^=r>>>24))+((1540483477*(r>>>16)&65535)<<16)),n-=4,++a;switch(n){case 3:i^=(255&t.charCodeAt(a+2))<<16;case 2:i^=(255&t.charCodeAt(a+1))<<8;case 1:i=1540483477*(65535&(i^=255&t.charCodeAt(a)))+((1540483477*(i>>>16)&65535)<<16);}return i=1540483477*(65535&(i^=i>>>13))+((1540483477*(i>>>16)&65535)<<16),(i^=i>>>15)>>>0};})),la=sa,pa=ua;la.murmur3=sa,la.murmur2=pa;var ca=function(){this.ids=[],this.positions=[],this.indexed=!1;};ca.prototype.add=function(t,e,r,n){this.ids.push(fa(t)),this.positions.push(e,r,n);},ca.prototype.getPositions=function(t){for(var e=fa(t),r=0,n=this.ids.length-1;r>1;this.ids[i]>=e?n=i:r=i+1;}for(var a=[];this.ids[r]===e;)a.push({index:this.positions[3*r],start:this.positions[3*r+1],end:this.positions[3*r+2]}),r++;return a},ca.serialize=function(t,e){var r=new Float64Array(t.ids),n=new Uint32Array(t.positions);return function t(e,r,n,i){for(;n>1],o=n-1,s=i+1;;){do{o++;}while(e[o]a);if(o>=s)break;ya(e,o,s),ya(r,3*o,3*s),ya(r,3*o+1,3*s+1),ya(r,3*o+2,3*s+2);}s-nVa.max||o.yVa.max)&&(w("Geometry exceeds allowed extent, reduce your vector tile buffer size"),o.x=u(o.x,Va.min,Va.max),o.y=u(o.y,Va.min,Va.max));}return r}function Da(t,e,r,n,i){t.emplaceBack(2*e+(n+1)/2,2*r+(i+1)/2);}var La=function(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map((function(t){return t.id})),this.index=t.index,this.hasPattern=!1,this.layoutVertexArray=new ki,this.indexArray=new Li,this.segments=new ia,this.programConfigurations=new Ta(na,t.layers,t.zoom),this.stateDependentLayerIds=this.layers.filter((function(t){return t.isStateDependent()})).map((function(t){return t.id}));};function Ra(t,e){for(var r=0;r1){if(qa(t,e))return !0;for(var n=0;n1?r:r.sub(e)._mult(i)._add(e))}function Za(t,e){for(var r,n,i,a=!1,o=0;oe.y!=(i=r[u]).y>e.y&&e.x<(i.x-n.x)*(e.y-n.y)/(i.y-n.y)+n.x&&(a=!a);return a}function Xa(t,e){for(var r=!1,n=0,i=t.length-1;ne.y!=o.y>e.y&&e.x<(o.x-a.x)*(e.y-a.y)/(o.y-a.y)+a.x&&(r=!r);}return r}function Ja(t,e,r){var n=r[0],i=r[2];if(t.xi.x&&e.x>i.x||t.yi.y&&e.y>i.y)return !1;var a=_(t,e,r[0]);return a!==_(t,e,r[1])||a!==_(t,e,r[2])||a!==_(t,e,r[3])}function Ha(t,e,r){var n=e.paint.get(t).value;return "constant"===n.kind?n.value:r.programConfigurations.get(e.id).getMaxValue(t)}function Ya(t){return Math.sqrt(t[0]*t[0]+t[1]*t[1])}function $a(t,e,r,n,a){if(!e[0]&&!e[1])return t;var o=i.convert(e)._mult(a);"viewport"===r&&o._rotate(-n);for(var s=[],u=0;u=8192||p<0||p>=8192)){var c=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray,t.sortKey),h=c.vertexLength;Da(this.layoutVertexArray,l,p,-1,-1),Da(this.layoutVertexArray,l,p,1,-1),Da(this.layoutVertexArray,l,p,1,1),Da(this.layoutVertexArray,l,p,-1,1),this.indexArray.emplaceBack(h,h+1,h+2),this.indexArray.emplaceBack(h,h+3,h+2),c.vertexLength+=4,c.primitiveLength+=2;}}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,t,r,{},n);},Fn("CircleBucket",La,{omit:["layers"]});var Wa=new gi({"circle-sort-key":new yi(It.layout_circle["circle-sort-key"])}),Qa={paint:new gi({"circle-radius":new yi(It.paint_circle["circle-radius"]),"circle-color":new yi(It.paint_circle["circle-color"]),"circle-blur":new yi(It.paint_circle["circle-blur"]),"circle-opacity":new yi(It.paint_circle["circle-opacity"]),"circle-translate":new fi(It.paint_circle["circle-translate"]),"circle-translate-anchor":new fi(It.paint_circle["circle-translate-anchor"]),"circle-pitch-scale":new fi(It.paint_circle["circle-pitch-scale"]),"circle-pitch-alignment":new fi(It.paint_circle["circle-pitch-alignment"]),"circle-stroke-width":new yi(It.paint_circle["circle-stroke-width"]),"circle-stroke-color":new yi(It.paint_circle["circle-stroke-color"]),"circle-stroke-opacity":new yi(It.paint_circle["circle-stroke-opacity"])}),layout:Wa},to="undefined"!=typeof Float32Array?Float32Array:Array;function eo(t){return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}function ro(t,e,r){var n=e[0],i=e[1],a=e[2],o=e[3],s=e[4],u=e[5],l=e[6],p=e[7],c=e[8],h=e[9],f=e[10],y=e[11],d=e[12],m=e[13],v=e[14],g=e[15],x=r[0],b=r[1],w=r[2],_=r[3];return t[0]=x*n+b*s+w*c+_*d,t[1]=x*i+b*u+w*h+_*m,t[2]=x*a+b*l+w*f+_*v,t[3]=x*o+b*p+w*y+_*g,t[4]=(x=r[4])*n+(b=r[5])*s+(w=r[6])*c+(_=r[7])*d,t[5]=x*i+b*u+w*h+_*m,t[6]=x*a+b*l+w*f+_*v,t[7]=x*o+b*p+w*y+_*g,t[8]=(x=r[8])*n+(b=r[9])*s+(w=r[10])*c+(_=r[11])*d,t[9]=x*i+b*u+w*h+_*m,t[10]=x*a+b*l+w*f+_*v,t[11]=x*o+b*p+w*y+_*g,t[12]=(x=r[12])*n+(b=r[13])*s+(w=r[14])*c+(_=r[15])*d,t[13]=x*i+b*u+w*h+_*m,t[14]=x*a+b*l+w*f+_*v,t[15]=x*o+b*p+w*y+_*g,t}Math.hypot||(Math.hypot=function(){for(var t=arguments,e=0,r=arguments.length;r--;)e+=t[r]*t[r];return Math.sqrt(e)});var no,io=ro;function ao(t,e,r){var n=e[0],i=e[1],a=e[2],o=e[3];return t[0]=r[0]*n+r[4]*i+r[8]*a+r[12]*o,t[1]=r[1]*n+r[5]*i+r[9]*a+r[13]*o,t[2]=r[2]*n+r[6]*i+r[10]*a+r[14]*o,t[3]=r[3]*n+r[7]*i+r[11]*a+r[15]*o,t}no=new to(3),to!=Float32Array&&(no[0]=0,no[1]=0,no[2]=0),function(){var t=new to(4);to!=Float32Array&&(t[0]=0,t[1]=0,t[2]=0,t[3]=0);}();var oo=(function(){var t=new to(2);to!=Float32Array&&(t[0]=0,t[1]=0);}(),function(t){function e(e){t.call(this,e,Qa);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.createBucket=function(t){return new La(t)},e.prototype.queryRadius=function(t){var e=t;return Ha("circle-radius",this,e)+Ha("circle-stroke-width",this,e)+Ya(this.paint.get("circle-translate"))},e.prototype.queryIntersectsFeature=function(t,e,r,n,i,a,o,s){for(var u=$a(t,this.paint.get("circle-translate"),this.paint.get("circle-translate-anchor"),a.angle,o),l=this.paint.get("circle-radius").evaluate(e,r)+this.paint.get("circle-stroke-width").evaluate(e,r),p="map"===this.paint.get("circle-pitch-alignment"),c=p?u:function(t,e){return t.map((function(t){return so(t,e)}))}(u,s),h=p?l*o:l,f=0,y=n;ft.width||i.height>t.height||r.x>t.width-i.width||r.y>t.height-i.height)throw new RangeError("out of range source coordinates for image copy");if(i.width>e.width||i.height>e.height||n.x>e.width-i.width||n.y>e.height-i.height)throw new RangeError("out of range destination coordinates for image copy");for(var o=t.data,s=e.data,u=0;u80*r){n=a=t[0],i=o=t[1];for(var y=r;ya&&(a=s),u>o&&(o=u);l=0!==(l=Math.max(a-n,o-i))?1/l:0;}return Io(h,f,r,n,i,l),f}function So(t,e,r,n,i){var a,o;if(i===Jo(t,e,r,n)>0)for(a=e;a=e;a-=n)o=Go(a,t[a],t[a+1],o);return o&&Oo(o,o.next)&&(Zo(o),o=o.next),o}function ko(t,e){if(!t)return t;e||(e=t);var r,n=t;do{if(r=!1,n.steiner||!Oo(n,n.next)&&0!==Ro(n.prev,n,n.next))n=n.next;else {if(Zo(n),(n=e=n.prev)===n.next)break;r=!0;}}while(r||n!==e);return e}function Io(t,e,r,n,i,a,o){if(t){!o&&a&&function(t,e,r,n){var i=t;do{null===i.z&&(i.z=Vo(i.x,i.y,e,r,n)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next;}while(i!==t);i.prevZ.nextZ=null,i.prevZ=null,function(t){var e,r,n,i,a,o,s,u,l=1;do{for(r=t,t=null,a=null,o=0;r;){for(o++,n=r,s=0,e=0;e0||u>0&&n;)0!==s&&(0===u||!n||r.z<=n.z)?(i=r,r=r.nextZ,s--):(i=n,n=n.nextZ,u--),a?a.nextZ=i:t=i,i.prevZ=a,a=i;r=n;}a.nextZ=null,l*=2;}while(o>1)}(i);}(t,n,i,a);for(var s,u,l=t;t.prev!==t.next;)if(s=t.prev,u=t.next,a?Co(t,n,i,a):zo(t))e.push(s.i/r),e.push(t.i/r),e.push(u.i/r),Zo(t),t=u.next,l=u.next;else if((t=u)===l){o?1===o?Io(t=Mo(ko(t),e,r),e,r,n,i,a,2):2===o&&Eo(t,e,r,n,i,a):Io(ko(t),e,r,n,i,a,1);break}}}function zo(t){var e=t.prev,r=t,n=t.next;if(Ro(e,r,n)>=0)return !1;for(var i=t.next.next;i!==t.prev;){if(Do(e.x,e.y,r.x,r.y,n.x,n.y,i.x,i.y)&&Ro(i.prev,i,i.next)>=0)return !1;i=i.next;}return !0}function Co(t,e,r,n){var i=t.prev,a=t,o=t.next;if(Ro(i,a,o)>=0)return !1;for(var s=i.x>a.x?i.x>o.x?i.x:o.x:a.x>o.x?a.x:o.x,u=i.y>a.y?i.y>o.y?i.y:o.y:a.y>o.y?a.y:o.y,l=Vo(i.x=l&&h&&h.z<=p;){if(c!==t.prev&&c!==t.next&&Do(i.x,i.y,a.x,a.y,o.x,o.y,c.x,c.y)&&Ro(c.prev,c,c.next)>=0)return !1;if(c=c.prevZ,h!==t.prev&&h!==t.next&&Do(i.x,i.y,a.x,a.y,o.x,o.y,h.x,h.y)&&Ro(h.prev,h,h.next)>=0)return !1;h=h.nextZ;}for(;c&&c.z>=l;){if(c!==t.prev&&c!==t.next&&Do(i.x,i.y,a.x,a.y,o.x,o.y,c.x,c.y)&&Ro(c.prev,c,c.next)>=0)return !1;c=c.prevZ;}for(;h&&h.z<=p;){if(h!==t.prev&&h!==t.next&&Do(i.x,i.y,a.x,a.y,o.x,o.y,h.x,h.y)&&Ro(h.prev,h,h.next)>=0)return !1;h=h.nextZ;}return !0}function Mo(t,e,r){var n=t;do{var i=n.prev,a=n.next.next;!Oo(i,a)&&Uo(i,n,n.next,a)&&No(i,a)&&No(a,i)&&(e.push(i.i/r),e.push(n.i/r),e.push(a.i/r),Zo(n),Zo(n.next),n=t=a),n=n.next;}while(n!==t);return ko(n)}function Eo(t,e,r,n,i,a){var o=t;do{for(var s=o.next.next;s!==o.prev;){if(o.i!==s.i&&Lo(o,s)){var u=Ko(o,s);return o=ko(o,o.next),u=ko(u,u.next),Io(o,e,r,n,i,a),void Io(u,e,r,n,i,a)}s=s.next;}o=o.next;}while(o!==t)}function To(t,e){return t.x-e.x}function Po(t,e){if(e=function(t,e){var r,n=e,i=t.x,a=t.y,o=-1/0;do{if(a<=n.y&&a>=n.next.y&&n.next.y!==n.y){var s=n.x+(a-n.y)*(n.next.x-n.x)/(n.next.y-n.y);if(s<=i&&s>o){if(o=s,s===i){if(a===n.y)return n;if(a===n.next.y)return n.next}r=n.x=n.x&&n.x>=p&&i!==n.x&&Do(ar.x||n.x===r.x&&Bo(r,n)))&&(r=n,h=u)),n=n.next;}while(n!==l);return r}(t,e)){var r=Ko(e,t);ko(e,e.next),ko(r,r.next);}}function Bo(t,e){return Ro(t.prev,t,e.prev)<0&&Ro(e.next,t,t.next)<0}function Vo(t,e,r,n,i){return (t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=32767*(t-r)*i)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=32767*(e-n)*i)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function Fo(t){var e=t,r=t;do{(e.x=0&&(t-o)*(n-s)-(r-o)*(e-s)>=0&&(r-o)*(a-s)-(i-o)*(n-s)>=0}function Lo(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){var r=t;do{if(r.i!==t.i&&r.next.i!==t.i&&r.i!==e.i&&r.next.i!==e.i&&Uo(r,r.next,t,e))return !0;r=r.next;}while(r!==t);return !1}(t,e)&&(No(t,e)&&No(e,t)&&function(t,e){var r=t,n=!1,i=(t.x+e.x)/2,a=(t.y+e.y)/2;do{r.y>a!=r.next.y>a&&r.next.y!==r.y&&i<(r.next.x-r.x)*(a-r.y)/(r.next.y-r.y)+r.x&&(n=!n),r=r.next;}while(r!==t);return n}(t,e)&&(Ro(t.prev,t,e.prev)||Ro(t,e.prev,e))||Oo(t,e)&&Ro(t.prev,t,t.next)>0&&Ro(e.prev,e,e.next)>0)}function Ro(t,e,r){return (e.y-t.y)*(r.x-e.x)-(e.x-t.x)*(r.y-e.y)}function Oo(t,e){return t.x===e.x&&t.y===e.y}function Uo(t,e,r,n){var i=qo(Ro(t,e,r)),a=qo(Ro(t,e,n)),o=qo(Ro(r,n,t)),s=qo(Ro(r,n,e));return i!==a&&o!==s||!(0!==i||!jo(t,r,e))||!(0!==a||!jo(t,n,e))||!(0!==o||!jo(r,t,n))||!(0!==s||!jo(r,e,n))}function jo(t,e,r){return e.x<=Math.max(t.x,r.x)&&e.x>=Math.min(t.x,r.x)&&e.y<=Math.max(t.y,r.y)&&e.y>=Math.min(t.y,r.y)}function qo(t){return t>0?1:t<0?-1:0}function No(t,e){return Ro(t.prev,t,t.next)<0?Ro(t,e,t.next)>=0&&Ro(t,t.prev,e)>=0:Ro(t,e,t.prev)<0||Ro(t,t.next,e)<0}function Ko(t,e){var r=new Xo(t.i,t.x,t.y),n=new Xo(e.i,e.x,e.y),i=t.next,a=e.prev;return t.next=e,e.prev=t,r.next=i,i.prev=r,n.next=r,r.prev=n,a.next=n,n.prev=a,n}function Go(t,e,r,n){var i=new Xo(t,e,r);return n?(i.next=n.next,i.prev=n,n.next.prev=i,n.next=i):(i.prev=i,i.next=i),i}function Zo(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ);}function Xo(t,e,r){this.i=t,this.x=e,this.y=r,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1;}function Jo(t,e,r,n){for(var i=0,a=e,o=r-n;an;){if(i-n>600){var o=i-n+1,s=r-n+1,u=Math.log(o),l=.5*Math.exp(2*u/3),p=.5*Math.sqrt(u*l*(o-l)/o)*(s-o/2<0?-1:1);t(e,r,Math.max(n,Math.floor(r-s*l/o+p)),Math.min(i,Math.floor(r+(o-s)*l/o+p)),a);}var c=e[r],h=n,f=i;for(Yo(e,n,r),a(e[i],c)>0&&Yo(e,n,i);h0;)f--;}0===a(e[n],c)?Yo(e,n,f):Yo(e,++f,i),f<=r&&(n=f+1),r<=f&&(i=f-1);}}(t,e,r||0,n||t.length-1,i||$o);}function Yo(t,e,r){var n=t[e];t[e]=t[r],t[r]=n;}function $o(t,e){return te?1:0}function Wo(t,e){var r=t.length;if(r<=1)return [t];for(var n,i,a=[],o=0;o1)for(var u=0;u0&&r.holes.push(n+=t[i-1].length);}return r},wo.default=_o;var rs=function(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map((function(t){return t.id})),this.index=t.index,this.hasPattern=!1,this.patternFeatures=[],this.layoutVertexArray=new ki,this.indexArray=new Li,this.indexArray2=new Ni,this.programConfigurations=new Ta(bo,t.layers,t.zoom),this.segments=new ia,this.segments2=new ia,this.stateDependentLayerIds=this.layers.filter((function(t){return t.isStateDependent()})).map((function(t){return t.id}));};rs.prototype.populate=function(t,e,r){this.hasPattern=ts("fill",this.layers,e);for(var n=this.layers[0].layout.get("fill-sort-key"),i=[],a=0,o=t;a>3;}if(a--,1===n||2===n)o+=t.readSVarint(),s+=t.readSVarint(),1===n&&(e&&u.push(e),e=[]),e.push(new i(o,s));else {if(7!==n)throw new Error("unknown command "+n);e&&e.push(e[0].clone());}}return e&&u.push(e),u},us.prototype.bbox=function(){var t=this._pbf;t.pos=this._geometry;for(var e=t.readVarint()+t.pos,r=1,n=0,i=0,a=0,o=1/0,s=-1/0,u=1/0,l=-1/0;t.pos>3;}if(n--,1===r||2===r)(i+=t.readSVarint())s&&(s=i),(a+=t.readSVarint())l&&(l=a);else if(7!==r)throw new Error("unknown command "+r)}return [o,u,s,l]},us.prototype.toGeoJSON=function(t,e,r){var n,i,a=this.extent*Math.pow(2,r),o=this.extent*t,s=this.extent*e,u=this.loadGeometry(),l=us.types[this.type];function p(t){for(var e=0;e>3;e=1===n?t.readString():2===n?t.readFloat():3===n?t.readDouble():4===n?t.readVarint64():5===n?t.readVarint():6===n?t.readSVarint():7===n?t.readBoolean():null;}return e}(r));}function ys(t,e,r){if(3===t){var n=new cs(r,r.readVarint()+r.pos);n.length&&(e[n.name]=n);}}hs.prototype.feature=function(t){if(t<0||t>=this._features.length)throw new Error("feature index out of bounds");this._pbf.pos=this._features[t];var e=this._pbf.readVarint()+this._pbf.pos;return new ss(this._pbf,e,this.extent,this._keys,this._values)};var ds={VectorTile:function(t,e){this.layers=t.readFields(ys,{},e);},VectorTileFeature:ss,VectorTileLayer:cs},ms=ds.VectorTileFeature.types,vs=Math.pow(2,13);function gs(t,e,r,n,i,a,o,s){t.emplaceBack(e,r,2*Math.floor(n*vs)+o,i*vs*2,a*vs*2,Math.round(s));}var xs=function(t){this.zoom=t.zoom,this.overscaling=t.overscaling,this.layers=t.layers,this.layerIds=this.layers.map((function(t){return t.id})),this.index=t.index,this.hasPattern=!1,this.layoutVertexArray=new zi,this.indexArray=new Li,this.programConfigurations=new Ta(os,t.layers,t.zoom),this.segments=new ia,this.stateDependentLayerIds=this.layers.filter((function(t){return t.isStateDependent()})).map((function(t){return t.id}));};function bs(t,e){return t.x===e.x&&(t.x<0||t.x>8192)||t.y===e.y&&(t.y<0||t.y>8192)}xs.prototype.populate=function(t,e,r){this.features=[],this.hasPattern=ts("fill-extrusion",this.layers,e);for(var n=0,i=t;n8192}))||P.every((function(t){return t.y<0}))||P.every((function(t){return t.y>8192}))))for(var d=0,m=0;m=1){var g=y[m-1];if(!bs(v,g)){c.vertexLength+4>ia.MAX_VERTEX_ARRAY_LENGTH&&(c=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray));var x=v.sub(g)._perp()._unit(),b=g.dist(v);d+b>32768&&(d=0),gs(this.layoutVertexArray,v.x,v.y,x.x,x.y,0,0,d),gs(this.layoutVertexArray,v.x,v.y,x.x,x.y,0,1,d),gs(this.layoutVertexArray,g.x,g.y,x.x,x.y,0,0,d+=b),gs(this.layoutVertexArray,g.x,g.y,x.x,x.y,0,1,d);var w=c.vertexLength;this.indexArray.emplaceBack(w,w+2,w+1),this.indexArray.emplaceBack(w+1,w+2,w+3),c.vertexLength+=4,c.primitiveLength+=2;}}}}if(c.vertexLength+u>ia.MAX_VERTEX_ARRAY_LENGTH&&(c=this.segments.prepareSegment(u,this.layoutVertexArray,this.indexArray)),"Polygon"===ms[t.type]){for(var _=[],A=[],S=c.vertexLength,k=0,I=s;k=2&&t[u-1].equals(t[u-2]);)u--;for(var l=0;l0;if(A&&v>l){var k=p.dist(f);if(k>2*c){var I=p.sub(p.sub(f)._mult(c/k)._round());this.updateDistance(f,I),this.addCurrentVertex(I,d,0,0,h),f=I;}}var z=f&&y,C=z?r:s?"butt":n;if(z&&"round"===C&&(wi&&(C="bevel"),"bevel"===C&&(w>2&&(C="flipbevel"),w100)g=m.mult(-1);else {var M=w*d.add(m).mag()/d.sub(m).mag();g._perp()._mult(M*(S?-1:1));}this.addCurrentVertex(p,g,0,0,h),this.addCurrentVertex(p,g.mult(-1),0,0,h);}else if("bevel"===C||"fakeround"===C){var E=-Math.sqrt(w*w-1),T=S?E:0,P=S?0:E;if(f&&this.addCurrentVertex(p,d,T,P,h),"fakeround"===C)for(var B=Math.round(180*_/Math.PI/20),V=1;V2*c){var U=p.add(y.sub(p)._mult(c/O)._round());this.updateDistance(p,U),this.addCurrentVertex(U,m,0,0,h),p=U;}}}}},Ms.prototype.addCurrentVertex=function(t,e,r,n,i,a){void 0===a&&(a=!1);var o=e.y*n-e.x,s=-e.y-e.x*n;this.addHalfVertex(t,e.x+e.y*r,e.y-e.x*r,a,!1,r,i),this.addHalfVertex(t,o,s,a,!0,-n,i),this.distance>Cs/2&&0===this.totalDistance&&(this.distance=0,this.addCurrentVertex(t,e,r,n,i,a));},Ms.prototype.addHalfVertex=function(t,e,r,n,i,a,o){var s=.5*this.scaledDistance;this.layoutVertexArray.emplaceBack((t.x<<1)+(n?1:0),(t.y<<1)+(i?1:0),Math.round(63*e)+128,Math.round(63*r)+128,1+(0===a?0:a<0?-1:1)|(63&s)<<2,s>>6);var u=o.vertexLength++;this.e1>=0&&this.e2>=0&&(this.indexArray.emplaceBack(this.e1,this.e2,u),o.primitiveLength++),i?this.e2=u:this.e1=u;},Ms.prototype.updateScaledDistance=function(){this.scaledDistance=this.totalDistance>0?(this.clipStart+(this.clipEnd-this.clipStart)*this.distance/this.totalDistance)*(Cs-1):this.distance;},Ms.prototype.updateDistance=function(t,e){this.distance+=t.dist(e),this.updateScaledDistance();},Fn("LineBucket",Ms,{omit:["layers","patternFeatures"]});var Es=new gi({"line-cap":new fi(It.layout_line["line-cap"]),"line-join":new yi(It.layout_line["line-join"]),"line-miter-limit":new fi(It.layout_line["line-miter-limit"]),"line-round-limit":new fi(It.layout_line["line-round-limit"]),"line-sort-key":new yi(It.layout_line["line-sort-key"])}),Ts={paint:new gi({"line-opacity":new yi(It.paint_line["line-opacity"]),"line-color":new yi(It.paint_line["line-color"]),"line-translate":new fi(It.paint_line["line-translate"]),"line-translate-anchor":new fi(It.paint_line["line-translate-anchor"]),"line-width":new yi(It.paint_line["line-width"]),"line-gap-width":new yi(It.paint_line["line-gap-width"]),"line-offset":new yi(It.paint_line["line-offset"]),"line-blur":new yi(It.paint_line["line-blur"]),"line-dasharray":new mi(It.paint_line["line-dasharray"]),"line-pattern":new di(It.paint_line["line-pattern"]),"line-gradient":new vi(It.paint_line["line-gradient"])}),layout:Es},Ps=new(function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.possiblyEvaluate=function(e,r){return r=new ii(Math.floor(r.zoom),{now:r.now,fadeDuration:r.fadeDuration,zoomHistory:r.zoomHistory,transition:r.transition}),t.prototype.possiblyEvaluate.call(this,e,r)},e.prototype.evaluate=function(e,r,n,i){return r=p({},r,{zoom:Math.floor(r.zoom)}),t.prototype.evaluate.call(this,e,r,n,i)},e}(yi))(Ts.paint.properties["line-width"].specification);Ps.useIntegerZoom=!0;var Bs=function(t){function e(e){t.call(this,e,Ts);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype._handleSpecialPaintPropertyUpdate=function(t){"line-gradient"===t&&this._updateGradient();},e.prototype._updateGradient=function(){this.gradient=mo(this._transitionablePaint._values["line-gradient"].value.expression,"lineProgress"),this.gradientTexture=null;},e.prototype.recalculate=function(e,r){t.prototype.recalculate.call(this,e,r),this.paint._values["line-floorwidth"]=Ps.possiblyEvaluate(this._transitioningPaint._values["line-width"].value,e);},e.prototype.createBucket=function(t){return new Ms(t)},e.prototype.queryRadius=function(t){var e=t,r=Vs(Ha("line-width",this,e),Ha("line-gap-width",this,e)),n=Ha("line-offset",this,e);return r/2+Math.abs(n)+Ya(this.paint.get("line-translate"))},e.prototype.queryIntersectsFeature=function(t,e,r,n,a,o,s){var u=$a(t,this.paint.get("line-translate"),this.paint.get("line-translate-anchor"),o.angle,s),l=s/2*Vs(this.paint.get("line-width").evaluate(e,r),this.paint.get("line-gap-width").evaluate(e,r)),p=this.paint.get("line-offset").evaluate(e,r);return p&&(n=function(t,e){for(var r=[],n=new i(0,0),a=0;a=3)for(var a=0;a0?e+2*t:t}var Fs=Ai([{name:"a_pos_offset",components:4,type:"Int16"},{name:"a_data",components:4,type:"Uint16"},{name:"a_pixeloffset",components:4,type:"Int16"}],4),Ds=Ai([{name:"a_projected_pos",components:3,type:"Float32"}],4),Ls=(Ai([{name:"a_fade_opacity",components:1,type:"Uint32"}],4),Ai([{name:"a_placed",components:2,type:"Uint8"},{name:"a_shift",components:2,type:"Float32"}])),Rs=(Ai([{type:"Int16",name:"anchorPointX"},{type:"Int16",name:"anchorPointY"},{type:"Int16",name:"x1"},{type:"Int16",name:"y1"},{type:"Int16",name:"x2"},{type:"Int16",name:"y2"},{type:"Uint32",name:"featureIndex"},{type:"Uint16",name:"sourceLayerIndex"},{type:"Uint16",name:"bucketIndex"}]),Ai([{name:"a_pos",components:2,type:"Int16"},{name:"a_anchor_pos",components:2,type:"Int16"},{name:"a_extrude",components:2,type:"Int16"}],4)),Os=Ai([{name:"a_pos",components:2,type:"Float32"},{name:"a_radius",components:1,type:"Float32"},{name:"a_flags",components:2,type:"Int16"}],4);function Us(t,e,r){return t.sections.forEach((function(t){t.text=function(t,e,r){var n=e.layout.get("text-transform").evaluate(r,{});return "uppercase"===n?t=t.toLocaleUpperCase():"lowercase"===n&&(t=t.toLocaleLowerCase()),ni.applyArabicShaping&&(t=ni.applyArabicShaping(t)),t}(t.text,e,r);})),t}Ai([{name:"triangle",components:3,type:"Uint16"}]),Ai([{type:"Int16",name:"anchorX"},{type:"Int16",name:"anchorY"},{type:"Uint16",name:"glyphStartIndex"},{type:"Uint16",name:"numGlyphs"},{type:"Uint32",name:"vertexStartIndex"},{type:"Uint32",name:"lineStartIndex"},{type:"Uint32",name:"lineLength"},{type:"Uint16",name:"segment"},{type:"Uint16",name:"lowerSize"},{type:"Uint16",name:"upperSize"},{type:"Float32",name:"lineOffsetX"},{type:"Float32",name:"lineOffsetY"},{type:"Uint8",name:"writingMode"},{type:"Uint8",name:"placedOrientation"},{type:"Uint8",name:"hidden"},{type:"Uint32",name:"crossTileID"},{type:"Int16",name:"associatedIconIndex"}]),Ai([{type:"Int16",name:"anchorX"},{type:"Int16",name:"anchorY"},{type:"Int16",name:"rightJustifiedTextSymbolIndex"},{type:"Int16",name:"centerJustifiedTextSymbolIndex"},{type:"Int16",name:"leftJustifiedTextSymbolIndex"},{type:"Int16",name:"verticalPlacedTextSymbolIndex"},{type:"Int16",name:"placedIconSymbolIndex"},{type:"Int16",name:"verticalPlacedIconSymbolIndex"},{type:"Uint16",name:"key"},{type:"Uint16",name:"textBoxStartIndex"},{type:"Uint16",name:"textBoxEndIndex"},{type:"Uint16",name:"verticalTextBoxStartIndex"},{type:"Uint16",name:"verticalTextBoxEndIndex"},{type:"Uint16",name:"iconBoxStartIndex"},{type:"Uint16",name:"iconBoxEndIndex"},{type:"Uint16",name:"verticalIconBoxStartIndex"},{type:"Uint16",name:"verticalIconBoxEndIndex"},{type:"Uint16",name:"featureIndex"},{type:"Uint16",name:"numHorizontalGlyphVertices"},{type:"Uint16",name:"numVerticalGlyphVertices"},{type:"Uint16",name:"numIconVertices"},{type:"Uint16",name:"numVerticalIconVertices"},{type:"Uint16",name:"useRuntimeCollisionCircles"},{type:"Uint32",name:"crossTileID"},{type:"Float32",name:"textBoxScale"},{type:"Float32",components:2,name:"textOffset"},{type:"Float32",name:"collisionCircleDiameter"}]),Ai([{type:"Float32",name:"offsetX"}]),Ai([{type:"Int16",name:"x"},{type:"Int16",name:"y"},{type:"Int16",name:"tileUnitDistanceFromAnchor"}]);var js={"!":"︕","#":"#",$:"$","%":"%","&":"&","(":"︵",")":"︶","*":"*","+":"+",",":"︐","-":"︲",".":"・","/":"/",":":"︓",";":"︔","<":"︿","=":"=",">":"﹀","?":"︖","@":"@","[":"﹇","\\":"\","]":"﹈","^":"^",_:"︳","`":"`","{":"︷","|":"―","}":"︸","~":"~","¢":"¢","£":"£","¥":"¥","¦":"¦","¬":"¬","¯":" ̄","–":"︲","—":"︱","‘":"﹃","’":"﹄","“":"﹁","”":"﹂","…":"︙","‧":"・","₩":"₩","、":"︑","。":"︒","〈":"︿","〉":"﹀","《":"︽","》":"︾","「":"﹁","」":"﹂","『":"﹃","』":"﹄","【":"︻","】":"︼","〔":"︹","〕":"︺","〖":"︗","〗":"︘","!":"︕","(":"︵",")":"︶",",":"︐","-":"︲",".":"・",":":"︓",";":"︔","<":"︿",">":"﹀","?":"︖","[":"﹇","]":"﹈","_":"︳","{":"︷","|":"―","}":"︸","⦅":"︵","⦆":"︶","。":"︒","「":"﹁","」":"﹂"},qs=function(t,e,r,n,i){var a,o,s=8*i-n-1,u=(1<>1,p=-7,c=r?i-1:0,h=r?-1:1,f=t[e+c];for(c+=h,a=f&(1<<-p)-1,f>>=-p,p+=s;p>0;a=256*a+t[e+c],c+=h,p-=8);for(o=a&(1<<-p)-1,a>>=-p,p+=n;p>0;o=256*o+t[e+c],c+=h,p-=8);if(0===a)a=1-l;else {if(a===u)return o?NaN:1/0*(f?-1:1);o+=Math.pow(2,n),a-=l;}return (f?-1:1)*o*Math.pow(2,a-n)},Ns=function(t,e,r,n,i,a){var o,s,u,l=8*a-i-1,p=(1<>1,h=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,f=n?0:a-1,y=n?1:-1,d=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(s=isNaN(e)?1:0,o=p):(o=Math.floor(Math.log(e)/Math.LN2),e*(u=Math.pow(2,-o))<1&&(o--,u*=2),(e+=o+c>=1?h/u:h*Math.pow(2,1-c))*u>=2&&(o++,u/=2),o+c>=p?(s=0,o=p):o+c>=1?(s=(e*u-1)*Math.pow(2,i),o+=c):(s=e*Math.pow(2,c-1)*Math.pow(2,i),o=0));i>=8;t[r+f]=255&s,f+=y,s/=256,i-=8);for(o=o<0;t[r+f]=255&o,f+=y,o/=256,l-=8);t[r+f-y]|=128*d;},Ks=Gs;function Gs(t){this.buf=ArrayBuffer.isView&&ArrayBuffer.isView(t)?t:new Uint8Array(t||0),this.pos=0,this.type=0,this.length=this.buf.length;}Gs.Varint=0,Gs.Fixed64=1,Gs.Bytes=2,Gs.Fixed32=5;var Zs="undefined"==typeof TextDecoder?null:new TextDecoder("utf8");function Xs(t){return t.type===Gs.Bytes?t.readVarint()+t.pos:t.pos+1}function Js(t,e,r){return r?4294967296*e+(t>>>0):4294967296*(e>>>0)+(t>>>0)}function Hs(t,e,r){var n=e<=16383?1:e<=2097151?2:e<=268435455?3:Math.floor(Math.log(e)/(7*Math.LN2));r.realloc(n);for(var i=r.pos-1;i>=t;i--)r.buf[i+n]=r.buf[i];}function Ys(t,e){for(var r=0;r>>8,t[r+2]=e>>>16,t[r+3]=e>>>24;}function su(t,e){return (t[e]|t[e+1]<<8|t[e+2]<<16)+(t[e+3]<<24)}function uu(t,e,r){1===t&&r.readMessage(lu,e);}function lu(t,e,r){if(3===t){var n=r.readMessage(pu,{}),i=n.width,a=n.height,o=n.left,s=n.top,u=n.advance;e.push({id:n.id,bitmap:new ho({width:i+6,height:a+6},n.bitmap),metrics:{width:i,height:a,left:o,top:s,advance:u}});}}function pu(t,e,r){1===t?e.id=r.readVarint():2===t?e.bitmap=r.readBytes():3===t?e.width=r.readVarint():4===t?e.height=r.readVarint():5===t?e.left=r.readSVarint():6===t?e.top=r.readSVarint():7===t&&(e.advance=r.readVarint());}function cu(t){for(var e=0,r=0,n=0,i=t;n=0;h--){var f=o[h];if(!(c.w>f.w||c.h>f.h)){if(c.x=f.x,c.y=f.y,u=Math.max(u,c.y+c.h),s=Math.max(s,c.x+c.w),c.w===f.w&&c.h===f.h){var y=o.pop();h>3,a=this.pos;this.type=7&n,t(i,e,this),this.pos===a&&this.skip(n);}return e},readMessage:function(t,e){return this.readFields(t,e,this.readVarint()+this.pos)},readFixed32:function(){var t=au(this.buf,this.pos);return this.pos+=4,t},readSFixed32:function(){var t=su(this.buf,this.pos);return this.pos+=4,t},readFixed64:function(){var t=au(this.buf,this.pos)+4294967296*au(this.buf,this.pos+4);return this.pos+=8,t},readSFixed64:function(){var t=au(this.buf,this.pos)+4294967296*su(this.buf,this.pos+4);return this.pos+=8,t},readFloat:function(){var t=qs(this.buf,this.pos,!0,23,4);return this.pos+=4,t},readDouble:function(){var t=qs(this.buf,this.pos,!0,52,8);return this.pos+=8,t},readVarint:function(t){var e,r,n=this.buf;return e=127&(r=n[this.pos++]),r<128?e:(e|=(127&(r=n[this.pos++]))<<7,r<128?e:(e|=(127&(r=n[this.pos++]))<<14,r<128?e:(e|=(127&(r=n[this.pos++]))<<21,r<128?e:function(t,e,r){var n,i,a=r.buf;if(n=(112&(i=a[r.pos++]))>>4,i<128)return Js(t,n,e);if(n|=(127&(i=a[r.pos++]))<<3,i<128)return Js(t,n,e);if(n|=(127&(i=a[r.pos++]))<<10,i<128)return Js(t,n,e);if(n|=(127&(i=a[r.pos++]))<<17,i<128)return Js(t,n,e);if(n|=(127&(i=a[r.pos++]))<<24,i<128)return Js(t,n,e);if(n|=(1&(i=a[r.pos++]))<<31,i<128)return Js(t,n,e);throw new Error("Expected varint not more than 10 bytes")}(e|=(15&(r=n[this.pos]))<<28,t,this))))},readVarint64:function(){return this.readVarint(!0)},readSVarint:function(){var t=this.readVarint();return t%2==1?(t+1)/-2:t/2},readBoolean:function(){return Boolean(this.readVarint())},readString:function(){var t=this.readVarint()+this.pos,e=this.pos;return this.pos=t,t-e>=12&&Zs?function(t,e,r){return Zs.decode(t.subarray(e,r))}(this.buf,e,t):function(t,e,r){for(var n="",i=e;i239?4:u>223?3:u>191?2:1;if(i+p>r)break;1===p?u<128&&(l=u):2===p?128==(192&(a=t[i+1]))&&(l=(31&u)<<6|63&a)<=127&&(l=null):3===p?(o=t[i+2],128==(192&(a=t[i+1]))&&128==(192&o)&&((l=(15&u)<<12|(63&a)<<6|63&o)<=2047||l>=55296&&l<=57343)&&(l=null)):4===p&&(o=t[i+2],s=t[i+3],128==(192&(a=t[i+1]))&&128==(192&o)&&128==(192&s)&&((l=(15&u)<<18|(63&a)<<12|(63&o)<<6|63&s)<=65535||l>=1114112)&&(l=null)),null===l?(l=65533,p=1):l>65535&&(l-=65536,n+=String.fromCharCode(l>>>10&1023|55296),l=56320|1023&l),n+=String.fromCharCode(l),i+=p;}return n}(this.buf,e,t)},readBytes:function(){var t=this.readVarint()+this.pos,e=this.buf.subarray(this.pos,t);return this.pos=t,e},readPackedVarint:function(t,e){if(this.type!==Gs.Bytes)return t.push(this.readVarint(e));var r=Xs(this);for(t=t||[];this.pos127;);else if(e===Gs.Bytes)this.pos=this.readVarint()+this.pos;else if(e===Gs.Fixed32)this.pos+=4;else {if(e!==Gs.Fixed64)throw new Error("Unimplemented type: "+e);this.pos+=8;}},writeTag:function(t,e){this.writeVarint(t<<3|e);},realloc:function(t){for(var e=this.length||16;e268435455||t<0?function(t,e){var r,n;if(t>=0?(r=t%4294967296|0,n=t/4294967296|0):(n=~(-t/4294967296),4294967295^(r=~(-t%4294967296))?r=r+1|0:(r=0,n=n+1|0)),t>=0x10000000000000000||t<-0x10000000000000000)throw new Error("Given varint doesn't fit into 10 bytes");e.realloc(10),function(t,e,r){r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,t>>>=7,r.buf[r.pos++]=127&t|128,r.buf[r.pos]=127&(t>>>=7);}(r,0,e),function(t,e){var r=(7&t)<<4;e.buf[e.pos++]|=r|((t>>>=3)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),t&&(e.buf[e.pos++]=127&t)))));}(n,e);}(t,this):(this.realloc(4),this.buf[this.pos++]=127&t|(t>127?128:0),t<=127||(this.buf[this.pos++]=127&(t>>>=7)|(t>127?128:0),t<=127||(this.buf[this.pos++]=127&(t>>>=7)|(t>127?128:0),t<=127||(this.buf[this.pos++]=t>>>7&127))));},writeSVarint:function(t){this.writeVarint(t<0?2*-t-1:2*t);},writeBoolean:function(t){this.writeVarint(Boolean(t));},writeString:function(t){t=String(t),this.realloc(4*t.length),this.pos++;var e=this.pos;this.pos=function(t,e,r){for(var n,i,a=0;a55295&&n<57344){if(!i){n>56319||a+1===e.length?(t[r++]=239,t[r++]=191,t[r++]=189):i=n;continue}if(n<56320){t[r++]=239,t[r++]=191,t[r++]=189,i=n;continue}n=i-55296<<10|n-56320|65536,i=null;}else i&&(t[r++]=239,t[r++]=191,t[r++]=189,i=null);n<128?t[r++]=n:(n<2048?t[r++]=n>>6|192:(n<65536?t[r++]=n>>12|224:(t[r++]=n>>18|240,t[r++]=n>>12&63|128),t[r++]=n>>6&63|128),t[r++]=63&n|128);}return r}(this.buf,t,this.pos);var r=this.pos-e;r>=128&&Hs(e,r,this),this.pos=e-1,this.writeVarint(r),this.pos+=r;},writeFloat:function(t){this.realloc(4),Ns(this.buf,t,this.pos,!0,23,4),this.pos+=4;},writeDouble:function(t){this.realloc(8),Ns(this.buf,t,this.pos,!0,52,8),this.pos+=8;},writeBytes:function(t){var e=t.length;this.writeVarint(e),this.realloc(e);for(var r=0;r=128&&Hs(r,n,this),this.pos=r-1,this.writeVarint(n),this.pos+=n;},writeMessage:function(t,e,r){this.writeTag(t,Gs.Bytes),this.writeRawMessage(e,r);},writePackedVarint:function(t,e){e.length&&this.writeMessage(t,Ys,e);},writePackedSVarint:function(t,e){e.length&&this.writeMessage(t,$s,e);},writePackedBoolean:function(t,e){e.length&&this.writeMessage(t,tu,e);},writePackedFloat:function(t,e){e.length&&this.writeMessage(t,Ws,e);},writePackedDouble:function(t,e){e.length&&this.writeMessage(t,Qs,e);},writePackedFixed32:function(t,e){e.length&&this.writeMessage(t,eu,e);},writePackedSFixed32:function(t,e){e.length&&this.writeMessage(t,ru,e);},writePackedFixed64:function(t,e){e.length&&this.writeMessage(t,nu,e);},writePackedSFixed64:function(t,e){e.length&&this.writeMessage(t,iu,e);},writeBytesField:function(t,e){this.writeTag(t,Gs.Bytes),this.writeBytes(e);},writeFixed32Field:function(t,e){this.writeTag(t,Gs.Fixed32),this.writeFixed32(e);},writeSFixed32Field:function(t,e){this.writeTag(t,Gs.Fixed32),this.writeSFixed32(e);},writeFixed64Field:function(t,e){this.writeTag(t,Gs.Fixed64),this.writeFixed64(e);},writeSFixed64Field:function(t,e){this.writeTag(t,Gs.Fixed64),this.writeSFixed64(e);},writeVarintField:function(t,e){this.writeTag(t,Gs.Varint),this.writeVarint(e);},writeSVarintField:function(t,e){this.writeTag(t,Gs.Varint),this.writeSVarint(e);},writeStringField:function(t,e){this.writeTag(t,Gs.Bytes),this.writeString(e);},writeFloatField:function(t,e){this.writeTag(t,Gs.Fixed32),this.writeFloat(e);},writeDoubleField:function(t,e){this.writeTag(t,Gs.Fixed64),this.writeDouble(e);},writeBooleanField:function(t,e){this.writeVarintField(t,Boolean(e));}};var hu=function(t,e){var r=e.pixelRatio,n=e.version,i=e.stretchX,a=e.stretchY,o=e.content;this.paddedRect=t,this.pixelRatio=r,this.stretchX=i,this.stretchY=a,this.content=o,this.version=n;},fu={tl:{configurable:!0},br:{configurable:!0},tlbr:{configurable:!0},displaySize:{configurable:!0}};fu.tl.get=function(){return [this.paddedRect.x+1,this.paddedRect.y+1]},fu.br.get=function(){return [this.paddedRect.x+this.paddedRect.w-1,this.paddedRect.y+this.paddedRect.h-1]},fu.tlbr.get=function(){return this.tl.concat(this.br)},fu.displaySize.get=function(){return [(this.paddedRect.w-2)/this.pixelRatio,(this.paddedRect.h-2)/this.pixelRatio]},Object.defineProperties(hu.prototype,fu);var yu=function(t,e){var r={},n={};this.haveRenderCallbacks=[];var i=[];this.addImages(t,r,i),this.addImages(e,n,i);var a=cu(i),o=new fo({width:a.w||1,height:a.h||1});for(var s in t){var u=t[s],l=r[s].paddedRect;fo.copy(u.data,o,{x:0,y:0},{x:l.x+1,y:l.y+1},u.data);}for(var p in e){var c=e[p],h=n[p].paddedRect,f=h.x+1,y=h.y+1,d=c.data.width,m=c.data.height;fo.copy(c.data,o,{x:0,y:0},{x:f,y:y},c.data),fo.copy(c.data,o,{x:0,y:m-1},{x:f,y:y-1},{width:d,height:1}),fo.copy(c.data,o,{x:0,y:0},{x:f,y:y+m},{width:d,height:1}),fo.copy(c.data,o,{x:d-1,y:0},{x:f-1,y:y},{width:1,height:m}),fo.copy(c.data,o,{x:0,y:0},{x:f+d,y:y},{width:1,height:m});}this.image=o,this.iconPositions=r,this.patternPositions=n;};yu.prototype.addImages=function(t,e,r){for(var n in t){var i=t[n],a={x:0,y:0,w:i.data.width+2,h:i.data.height+2};r.push(a),e[n]=new hu(a,i),i.hasRenderCallback&&this.haveRenderCallbacks.push(n);}},yu.prototype.patchUpdatedImages=function(t,e){for(var r in t.dispatchRenderCallbacks(this.haveRenderCallbacks),t.updatedImages)this.patchUpdatedImage(this.iconPositions[r],t.getImage(r),e),this.patchUpdatedImage(this.patternPositions[r],t.getImage(r),e);},yu.prototype.patchUpdatedImage=function(t,e,r){if(t&&e&&t.version!==e.version){t.version=e.version;var n=t.tl;r.update(e.data,void 0,{x:n[0],y:n[1]});}},Fn("ImagePosition",hu),Fn("ImageAtlas",yu);var du={horizontal:1,vertical:2,horizontalOnly:3},mu=function(){this.scale=1,this.fontStack="",this.imageName=null;};mu.forText=function(t,e){var r=new mu;return r.scale=t||1,r.fontStack=e,r},mu.forImage=function(t){var e=new mu;return e.imageName=t,e};var vu=function(){this.text="",this.sectionIndex=[],this.sections=[],this.imageSectionID=null;};function gu(t,e,r,n,i,a,o,s,u,l,p,c,h,f,y,d){var m,v=vu.fromFeature(t,i);c===du.vertical&&v.verticalizePunctuation();var g=ni.processBidirectionalText,x=ni.processStyledBidirectionalText;if(g&&1===v.sections.length){m=[];for(var b=0,w=g(v.toString(),ku(v,l,a,e,n,f,y));b0&&R>k&&(k=R);}else {var O=r[z.fontStack],U=O&&O[M];if(U&&U.rect)P=U.rect,T=U.metrics;else {var j=e[z.fontStack],q=j&&j[M];if(!q)continue;T=q.metrics;}E=24*(w-z.scale);}F?(t.verticalizable=!0,S.push({glyph:M,imageName:B,x:h,y:f+E,vertical:F,scale:z.scale,fontStack:z.fontStack,sectionIndex:C,metrics:T,rect:P}),h+=V*z.scale+l):(S.push({glyph:M,imageName:B,x:h,y:f+E,vertical:F,scale:z.scale,fontStack:z.fontStack,sectionIndex:C,metrics:T,rect:P}),h+=T.advance*z.scale+l);}0!==S.length&&(y=Math.max(h-l,y),zu(S,0,S.length-1,m,k)),h=0;var N=a*w+k;A.lineOffset=Math.max(k,_),f+=N,d=Math.max(N,d),++v;}else f+=a,++v;}var K,G=f- -17,Z=Iu(o),X=Z.horizontalAlign,J=Z.verticalAlign;(function(t,e,r,n,i,a,o,s,u){var l,p=(e-r)*i;l=a!==o?-s*n- -17:(-n*u+.5)*o;for(var c=0,h=t;c=0&&n>=t&&xu[this.text.charCodeAt(n)];n--)r--;this.text=this.text.substring(t,r),this.sectionIndex=this.sectionIndex.slice(t,r);},vu.prototype.substring=function(t,e){var r=new vu;return r.text=this.text.substring(t,e),r.sectionIndex=this.sectionIndex.slice(t,e),r.sections=this.sections,r},vu.prototype.toString=function(){return this.text},vu.prototype.getMaxScale=function(){var t=this;return this.sectionIndex.reduce((function(e,r){return Math.max(e,t.sections[r].scale)}),0)},vu.prototype.addTextSection=function(t,e){this.text+=t.text,this.sections.push(mu.forText(t.scale,t.fontStack||e));for(var r=this.sections.length-1,n=0;n=63743?null:++this.imageSectionID:(this.imageSectionID=57344,this.imageSectionID)};var xu={9:!0,10:!0,11:!0,12:!0,13:!0,32:!0},bu={};function wu(t,e,r,n,i,a){if(e.imageName){var o=n[e.imageName];return o?o.displaySize[0]*e.scale*24/a+i:0}var s=r[e.fontStack],u=s&&s[t];return u?u.metrics.advance*e.scale+i:0}function _u(t,e,r,n){var i=Math.pow(t-e,2);return n?t=0,c=0,h=0;h-r/2;){if(--o<0)return !1;s-=t[o].dist(a),a=t[o];}s+=t[o].dist(t[o+1]),o++;for(var u=[],l=0;sn;)l-=u.shift().angleDelta;if(l>i)return !1;o++,s+=p.dist(c);}return !0}function Fu(t){for(var e=0,r=0;rl){var y=(l-u)/f,d=je(c.x,h.x,y),m=je(c.y,h.y,y),v=new Mu(d,m,h.angleTo(c),p);return v._round(),!o||Vu(t,v,s,o,e)?v:void 0}u+=f;}}function Ou(t,e,r,n,i,a,o,s,u){var l=Du(n,a,o),p=Lu(n,i),c=p*o,h=0===t[0].x||t[0].x===u||0===t[0].y||t[0].y===u;return e-c=0&&w=0&&_=0&&f+p<=c){var A=new Mu(w,_,x,d);A._round(),i&&!Vu(e,A,o,i,a)||y.push(A);}}h+=g;}return u||y.length||s||(y=t(e,h/2,n,i,a,o,s,!0,l)),y}(t,h?e/2*s%e:(p/2+2*a)*o*s%e,e,l,r,c,h,!1,u)}function Uu(t,e,r,n,a){for(var o=[],s=0;s=n&&h.x>=n||(c.x>=n?c=new i(n,c.y+(n-c.x)/(h.x-c.x)*(h.y-c.y))._round():h.x>=n&&(h=new i(n,c.y+(n-c.x)/(h.x-c.x)*(h.y-c.y))._round()),c.y>=a&&h.y>=a||(c.y>=a?c=new i(c.x+(a-c.y)/(h.y-c.y)*(h.x-c.x),a)._round():h.y>=a&&(h=new i(c.x+(a-c.y)/(h.y-c.y)*(h.x-c.x),a)._round()),l&&c.equals(l[l.length-1])||o.push(l=[c]),l.push(h)))));}return o}function ju(t,e,r,n){var a=[],o=t.image,s=o.pixelRatio,u=o.paddedRect.w-2,l=o.paddedRect.h-2,p=t.right-t.left,c=t.bottom-t.top,h=o.stretchX||[[0,u]],f=o.stretchY||[[0,l]],y=function(t,e){return t+e[1]-e[0]},d=h.reduce(y,0),m=f.reduce(y,0),v=u-d,g=l-m,x=0,b=d,w=0,_=m,A=0,S=v,k=0,I=g;if(o.content&&n){var z=o.content;x=qu(h,0,z[0]),w=qu(f,0,z[1]),b=qu(h,z[0],z[2]),_=qu(f,z[1],z[3]),A=z[0]-x,k=z[1]-w,S=z[2]-z[0]-b,I=z[3]-z[1]-_;}var C=function(n,a,u,l){var h=Ku(n.stretch-x,b,p,t.left),f=Gu(n.fixed-A,S,n.stretch,d),y=Ku(a.stretch-w,_,c,t.top),v=Gu(a.fixed-k,I,a.stretch,m),g=Ku(u.stretch-x,b,p,t.left),z=Gu(u.fixed-A,S,u.stretch,d),C=Ku(l.stretch-w,_,c,t.top),M=Gu(l.fixed-k,I,l.stretch,m),E=new i(h,y),T=new i(g,y),P=new i(g,C),B=new i(h,C),V=new i(f/s,v/s),F=new i(z/s,M/s),D=e*Math.PI/180;if(D){var L=Math.sin(D),R=Math.cos(D),O=[R,-L,L,R];E._matMult(O),T._matMult(O),B._matMult(O),P._matMult(O);}var U=n.stretch+n.fixed,j=a.stretch+a.fixed;return {tl:E,tr:T,bl:B,br:P,tex:{x:o.paddedRect.x+1+U,y:o.paddedRect.y+1+j,w:u.stretch+u.fixed-U,h:l.stretch+l.fixed-j},writingMode:void 0,glyphOffset:[0,0],sectionIndex:0,pixelOffsetTL:V,pixelOffsetBR:F,minFontScaleX:S/s/p,minFontScaleY:I/s/c,isSDF:r}};if(n&&(o.stretchX||o.stretchY))for(var M=Nu(h,v,d),E=Nu(f,g,m),T=0;T0&&(y=Math.max(10,y),this.circleDiameter=y);}else {var d=o.top*s-u,m=o.bottom*s+u,v=o.left*s-u,g=o.right*s+u,x=o.collisionPadding;if(x&&(v-=x[0]*s,d-=x[1]*s,g+=x[2]*s,m+=x[3]*s),p){var b=new i(v,d),w=new i(g,d),_=new i(v,m),A=new i(g,m),S=p*Math.PI/180;b._rotate(S),w._rotate(S),_._rotate(S),A._rotate(S),v=Math.min(b.x,w.x,_.x,A.x),g=Math.max(b.x,w.x,_.x,A.x),d=Math.min(b.y,w.y,_.y,A.y),m=Math.max(b.y,w.y,_.y,A.y);}t.emplaceBack(e.x,e.y,v,d,g,m,r,n,a);}this.boxEndIndex=t.length;},Xu=function(t,e){if(void 0===t&&(t=[]),void 0===e&&(e=Ju),this.data=t,this.length=this.data.length,this.compare=e,this.length>0)for(var r=(this.length>>1)-1;r>=0;r--)this._down(r);};function Ju(t,e){return te?1:0}function Hu(t,e,r){void 0===e&&(e=1),void 0===r&&(r=!1);for(var n=1/0,a=1/0,o=-1/0,s=-1/0,u=t[0],l=0;lo)&&(o=p.x),(!l||p.y>s)&&(s=p.y);}var c=Math.min(o-n,s-a),h=c/2,f=new Xu([],Yu);if(0===c)return new i(n,a);for(var y=n;ym.d||!m.d)&&(m=g,r&&console.log("found best %d after %d probes",Math.round(1e4*g.d)/1e4,v)),g.max-m.d<=e||(f.push(new $u(g.p.x-(h=g.h/2),g.p.y-h,h,t)),f.push(new $u(g.p.x+h,g.p.y-h,h,t)),f.push(new $u(g.p.x-h,g.p.y+h,h,t)),f.push(new $u(g.p.x+h,g.p.y+h,h,t)),v+=4);}return r&&(console.log("num probes: "+v),console.log("best distance: "+m.d)),m.p}function Yu(t,e){return e.max-t.max}function $u(t,e,r,n){this.p=new i(t,e),this.h=r,this.d=function(t,e){for(var r=!1,n=1/0,i=0;it.y!=p.y>t.y&&t.x<(p.x-l.x)*(t.y-l.y)/(p.y-l.y)+l.x&&(r=!r),n=Math.min(n,Ga(t,l,p));}return (r?1:-1)*Math.sqrt(n)}(this.p,n),this.max=this.d+this.h*Math.SQRT2;}Xu.prototype.push=function(t){this.data.push(t),this.length++,this._up(this.length-1);},Xu.prototype.pop=function(){if(0!==this.length){var t=this.data[0],e=this.data.pop();return this.length--,this.length>0&&(this.data[0]=e,this._down(0)),t}},Xu.prototype.peek=function(){return this.data[0]},Xu.prototype._up=function(t){for(var e=this.data,r=this.compare,n=e[t];t>0;){var i=t-1>>1,a=e[i];if(r(n,a)>=0)break;e[t]=a,t=i;}e[t]=n;},Xu.prototype._down=function(t){for(var e=this.data,r=this.compare,n=this.length>>1,i=e[t];t=0)break;e[t]=o,t=a;}e[t]=i;};var Wu=Number.POSITIVE_INFINITY;function Qu(t,e){return e[1]!==Wu?function(t,e,r){var n=0,i=0;switch(e=Math.abs(e),r=Math.abs(r),t){case"top-right":case"top-left":case"top":i=r-7;break;case"bottom-right":case"bottom-left":case"bottom":i=7-r;}switch(t){case"top-right":case"bottom-right":case"right":n=-e;break;case"top-left":case"bottom-left":case"left":n=e;}return [n,i]}(t,e[0],e[1]):function(t,e){var r=0,n=0;e<0&&(e=0);var i=e/Math.sqrt(2);switch(t){case"top-right":case"top-left":n=i-7;break;case"bottom-right":case"bottom-left":n=7-i;break;case"bottom":n=7-e;break;case"top":n=e-7;}switch(t){case"top-right":case"bottom-right":r=-i;break;case"top-left":case"bottom-left":r=i;break;case"left":r=e;break;case"right":r=-e;}return [r,n]}(t,e[0])}function tl(t){switch(t){case"right":case"top-right":case"bottom-right":return "right";case"left":case"top-left":case"bottom-left":return "left"}return "center"}function el(t,e,r,n,a,o,s,u,l,p,c,h,f,y,d){var m=function(t,e,r,n,a,o,s,u){for(var l=n.layout.get("text-rotate").evaluate(o,{})*Math.PI/180,p=[],c=0,h=e.positionedLines;c32640&&w(t.layerIds[0]+': Value for "text-size" is >= 255. Reduce your "text-size".'):"composite"===v.kind&&((g=[128*y.compositeTextSizes[0].evaluate(s,{},d),128*y.compositeTextSizes[1].evaluate(s,{},d)])[0]>32640||g[1]>32640)&&w(t.layerIds[0]+': Value for "text-size" is >= 255. Reduce your "text-size".'),t.addSymbols(t.text,m,g,u,o,s,p,e,l.lineStartIndex,l.lineLength,f,d);for(var x=0,b=c;x=0;o--)if(n.dist(a[o])0)&&("constant"!==a.value.kind||a.value.value.length>0),l="constant"!==s.value.kind||!!s.value.value||Object.keys(s.parameters).length>0,p=i.get("symbol-sort-key");if(this.features=[],u||l){for(var c=e.iconDependencies,h=e.glyphDependencies,f=e.availableImages,y=new ii(this.zoom),d=0,m=t;d=0;for(var B=0,V=S.sections;B=0;s--)a[s]={x:e[s].x,y:e[s].y,tileUnitDistanceFromAnchor:i},s>0&&(i+=e[s-1].dist(e[s]));for(var u=0;u0},cl.prototype.hasIconData=function(){return this.icon.segments.get().length>0},cl.prototype.hasDebugData=function(){return this.textCollisionBox&&this.iconCollisionBox},cl.prototype.hasTextCollisionBoxData=function(){return this.hasDebugData()&&this.textCollisionBox.segments.get().length>0},cl.prototype.hasIconCollisionBoxData=function(){return this.hasDebugData()&&this.iconCollisionBox.segments.get().length>0},cl.prototype.addIndicesForPlacedSymbol=function(t,e){for(var r=t.placedSymbolArray.get(e),n=r.vertexStartIndex+4*r.numGlyphs,i=r.vertexStartIndex;i1||this.icon.segments.get().length>1)){this.symbolInstanceIndexes=this.getSortedSymbolIndexes(t),this.sortedAngle=t,this.text.indexArray.clear(),this.icon.indexArray.clear(),this.featureSortOrder=[];for(var r=0,n=this.symbolInstanceIndexes;r=0&&n.indexOf(t)===r&&e.addIndicesForPlacedSymbol(e.text,t);})),i.verticalPlacedTextSymbolIndex>=0&&this.addIndicesForPlacedSymbol(this.text,i.verticalPlacedTextSymbolIndex),i.placedIconSymbolIndex>=0&&this.addIndicesForPlacedSymbol(this.icon,i.placedIconSymbolIndex),i.verticalPlacedIconSymbolIndex>=0&&this.addIndicesForPlacedSymbol(this.icon,i.verticalPlacedIconSymbolIndex);}this.text.indexBuffer&&this.text.indexBuffer.updateData(this.text.indexArray),this.icon.indexBuffer&&this.icon.indexBuffer.updateData(this.icon.indexArray);}},Fn("SymbolBucket",cl,{omit:["layers","collisionBoxArray","features","compareText"]}),cl.MAX_GLYPHS=65535,cl.addDynamicAttributes=sl;var hl=new gi({"symbol-placement":new fi(It.layout_symbol["symbol-placement"]),"symbol-spacing":new fi(It.layout_symbol["symbol-spacing"]),"symbol-avoid-edges":new fi(It.layout_symbol["symbol-avoid-edges"]),"symbol-sort-key":new yi(It.layout_symbol["symbol-sort-key"]),"symbol-z-order":new fi(It.layout_symbol["symbol-z-order"]),"icon-allow-overlap":new fi(It.layout_symbol["icon-allow-overlap"]),"icon-ignore-placement":new fi(It.layout_symbol["icon-ignore-placement"]),"icon-optional":new fi(It.layout_symbol["icon-optional"]),"icon-rotation-alignment":new fi(It.layout_symbol["icon-rotation-alignment"]),"icon-size":new yi(It.layout_symbol["icon-size"]),"icon-text-fit":new fi(It.layout_symbol["icon-text-fit"]),"icon-text-fit-padding":new fi(It.layout_symbol["icon-text-fit-padding"]),"icon-image":new yi(It.layout_symbol["icon-image"]),"icon-rotate":new yi(It.layout_symbol["icon-rotate"]),"icon-padding":new fi(It.layout_symbol["icon-padding"]),"icon-keep-upright":new fi(It.layout_symbol["icon-keep-upright"]),"icon-offset":new yi(It.layout_symbol["icon-offset"]),"icon-anchor":new yi(It.layout_symbol["icon-anchor"]),"icon-pitch-alignment":new fi(It.layout_symbol["icon-pitch-alignment"]),"text-pitch-alignment":new fi(It.layout_symbol["text-pitch-alignment"]),"text-rotation-alignment":new fi(It.layout_symbol["text-rotation-alignment"]),"text-field":new yi(It.layout_symbol["text-field"]),"text-font":new yi(It.layout_symbol["text-font"]),"text-size":new yi(It.layout_symbol["text-size"]),"text-max-width":new yi(It.layout_symbol["text-max-width"]),"text-line-height":new fi(It.layout_symbol["text-line-height"]),"text-letter-spacing":new yi(It.layout_symbol["text-letter-spacing"]),"text-justify":new yi(It.layout_symbol["text-justify"]),"text-radial-offset":new yi(It.layout_symbol["text-radial-offset"]),"text-variable-anchor":new fi(It.layout_symbol["text-variable-anchor"]),"text-anchor":new yi(It.layout_symbol["text-anchor"]),"text-max-angle":new fi(It.layout_symbol["text-max-angle"]),"text-writing-mode":new fi(It.layout_symbol["text-writing-mode"]),"text-rotate":new yi(It.layout_symbol["text-rotate"]),"text-padding":new fi(It.layout_symbol["text-padding"]),"text-keep-upright":new fi(It.layout_symbol["text-keep-upright"]),"text-transform":new yi(It.layout_symbol["text-transform"]),"text-offset":new yi(It.layout_symbol["text-offset"]),"text-allow-overlap":new fi(It.layout_symbol["text-allow-overlap"]),"text-ignore-placement":new fi(It.layout_symbol["text-ignore-placement"]),"text-optional":new fi(It.layout_symbol["text-optional"])}),fl={paint:new gi({"icon-opacity":new yi(It.paint_symbol["icon-opacity"]),"icon-color":new yi(It.paint_symbol["icon-color"]),"icon-halo-color":new yi(It.paint_symbol["icon-halo-color"]),"icon-halo-width":new yi(It.paint_symbol["icon-halo-width"]),"icon-halo-blur":new yi(It.paint_symbol["icon-halo-blur"]),"icon-translate":new fi(It.paint_symbol["icon-translate"]),"icon-translate-anchor":new fi(It.paint_symbol["icon-translate-anchor"]),"text-opacity":new yi(It.paint_symbol["text-opacity"]),"text-color":new yi(It.paint_symbol["text-color"],{runtimeType:Rt,getOverride:function(t){return t.textColor},hasOverride:function(t){return !!t.textColor}}),"text-halo-color":new yi(It.paint_symbol["text-halo-color"]),"text-halo-width":new yi(It.paint_symbol["text-halo-width"]),"text-halo-blur":new yi(It.paint_symbol["text-halo-blur"]),"text-translate":new fi(It.paint_symbol["text-translate"]),"text-translate-anchor":new fi(It.paint_symbol["text-translate-anchor"])}),layout:hl},yl=function(t){this.type=t.property.overrides?t.property.overrides.runtimeType:Vt,this.defaultValue=t;};yl.prototype.evaluate=function(t){if(t.formattedSection){var e=this.defaultValue.property.overrides;if(e&&e.hasOverride(t.formattedSection))return e.getOverride(t.formattedSection)}return t.feature&&t.featureState?this.defaultValue.evaluate(t.feature,t.featureState):this.defaultValue.property.specification.default},yl.prototype.eachChild=function(t){this.defaultValue.isConstant()||t(this.defaultValue.value._styleExpression.expression);},yl.prototype.outputDefined=function(){return !1},yl.prototype.serialize=function(){return null},Fn("FormatSectionOverride",yl,{omit:["defaultValue"]});var dl=function(t){function e(e){t.call(this,e,fl);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.recalculate=function(e,r){if(t.prototype.recalculate.call(this,e,r),"auto"===this.layout.get("icon-rotation-alignment")&&(this.layout._values["icon-rotation-alignment"]="point"!==this.layout.get("symbol-placement")?"map":"viewport"),"auto"===this.layout.get("text-rotation-alignment")&&(this.layout._values["text-rotation-alignment"]="point"!==this.layout.get("symbol-placement")?"map":"viewport"),"auto"===this.layout.get("text-pitch-alignment")&&(this.layout._values["text-pitch-alignment"]=this.layout.get("text-rotation-alignment")),"auto"===this.layout.get("icon-pitch-alignment")&&(this.layout._values["icon-pitch-alignment"]=this.layout.get("icon-rotation-alignment")),"point"===this.layout.get("symbol-placement")){var n=this.layout.get("text-writing-mode");if(n){for(var i=[],a=0,o=n;a",targetMapId:n,sourceMapId:a.mapId});}}},Ml.prototype.receive=function(t){var e=t.data,r=e.id;if(r&&(!e.targetMapId||this.mapId===e.targetMapId))if(""===e.type){delete this.tasks[r];var n=this.cancelCallbacks[r];delete this.cancelCallbacks[r],n&&n();}else S()||e.mustQueue?(this.tasks[r]=e,this.taskQueue.push(r),this.invoker.trigger()):this.processTask(r,e);},Ml.prototype.process=function(){if(this.taskQueue.length){var t=this.taskQueue.shift(),e=this.tasks[t];delete this.tasks[t],this.taskQueue.length&&this.invoker.trigger(),e&&this.processTask(t,e);}},Ml.prototype.processTask=function(t,e){var r=this;if(""===e.type){var n=this.callbacks[t];delete this.callbacks[t],n&&(e.error?n(Un(e.error)):n(null,Un(e.data)));}else {var i=!1,a=z(this.globalScope)?void 0:[],o=e.hasCallback?function(e,n){i=!0,delete r.cancelCallbacks[t],r.target.postMessage({id:t,type:"",sourceMapId:r.mapId,error:e?On(e):null,data:On(n,a)},a);}:function(t){i=!0;},s=null,u=Un(e.data);if(this.parent[e.type])s=this.parent[e.type](e.sourceMapId,u,o);else if(this.parent.getWorkerSource){var l=e.type.split(".");s=this.parent.getWorkerSource(e.sourceMapId,l[0],u.source)[l[1]](u,o);}else o(new Error("Could not find function "+e.type));!i&&s&&s.cancel&&(this.cancelCallbacks[t]=s.cancel);}},Ml.prototype.remove=function(){this.invoker.remove(),this.target.removeEventListener("message",this.receive,!1);};var Tl=function(t,e){t&&(e?this.setSouthWest(t).setNorthEast(e):4===t.length?this.setSouthWest([t[0],t[1]]).setNorthEast([t[2],t[3]]):this.setSouthWest(t[0]).setNorthEast(t[1]));};Tl.prototype.setNorthEast=function(t){return this._ne=t instanceof Pl?new Pl(t.lng,t.lat):Pl.convert(t),this},Tl.prototype.setSouthWest=function(t){return this._sw=t instanceof Pl?new Pl(t.lng,t.lat):Pl.convert(t),this},Tl.prototype.extend=function(t){var e,r,n=this._sw,i=this._ne;if(t instanceof Pl)e=t,r=t;else {if(!(t instanceof Tl))return Array.isArray(t)?4===t.length||t.every(Array.isArray)?this.extend(Tl.convert(t)):this.extend(Pl.convert(t)):this;if(r=t._ne,!(e=t._sw)||!r)return this}return n||i?(n.lng=Math.min(e.lng,n.lng),n.lat=Math.min(e.lat,n.lat),i.lng=Math.max(r.lng,i.lng),i.lat=Math.max(r.lat,i.lat)):(this._sw=new Pl(e.lng,e.lat),this._ne=new Pl(r.lng,r.lat)),this},Tl.prototype.getCenter=function(){return new Pl((this._sw.lng+this._ne.lng)/2,(this._sw.lat+this._ne.lat)/2)},Tl.prototype.getSouthWest=function(){return this._sw},Tl.prototype.getNorthEast=function(){return this._ne},Tl.prototype.getNorthWest=function(){return new Pl(this.getWest(),this.getNorth())},Tl.prototype.getSouthEast=function(){return new Pl(this.getEast(),this.getSouth())},Tl.prototype.getWest=function(){return this._sw.lng},Tl.prototype.getSouth=function(){return this._sw.lat},Tl.prototype.getEast=function(){return this._ne.lng},Tl.prototype.getNorth=function(){return this._ne.lat},Tl.prototype.toArray=function(){return [this._sw.toArray(),this._ne.toArray()]},Tl.prototype.toString=function(){return "LngLatBounds("+this._sw.toString()+", "+this._ne.toString()+")"},Tl.prototype.isEmpty=function(){return !(this._sw&&this._ne)},Tl.prototype.contains=function(t){var e=Pl.convert(t),r=e.lng,n=e.lat,i=this._sw.lng<=r&&r<=this._ne.lng;return this._sw.lng>this._ne.lng&&(i=this._sw.lng>=r&&r>=this._ne.lng),this._sw.lat<=n&&n<=this._ne.lat&&i},Tl.convert=function(t){return !t||t instanceof Tl?t:new Tl(t)};var Pl=function(t,e){if(isNaN(t)||isNaN(e))throw new Error("Invalid LngLat object: ("+t+", "+e+")");if(this.lng=+t,this.lat=+e,this.lat>90||this.lat<-90)throw new Error("Invalid LngLat latitude value: must be between -90 and 90")};Pl.prototype.wrap=function(){return new Pl(l(this.lng,-180,180),this.lat)},Pl.prototype.toArray=function(){return [this.lng,this.lat]},Pl.prototype.toString=function(){return "LngLat("+this.lng+", "+this.lat+")"},Pl.prototype.distanceTo=function(t){var e=Math.PI/180,r=this.lat*e,n=t.lat*e,i=Math.sin(r)*Math.sin(n)+Math.cos(r)*Math.cos(n)*Math.cos((t.lng-this.lng)*e);return 6371008.8*Math.acos(Math.min(i,1))},Pl.prototype.toBounds=function(t){void 0===t&&(t=0);var e=360*t/40075017,r=e/Math.cos(Math.PI/180*this.lat);return new Tl(new Pl(this.lng-r,this.lat-e),new Pl(this.lng+r,this.lat+e))},Pl.convert=function(t){if(t instanceof Pl)return t;if(Array.isArray(t)&&(2===t.length||3===t.length))return new Pl(Number(t[0]),Number(t[1]));if(!Array.isArray(t)&&"object"==typeof t&&null!==t)return new Pl(Number("lng"in t?t.lng:t.lon),Number(t.lat));throw new Error("`LngLatLike` argument must be specified as a LngLat instance, an object {lng: , lat: }, an object {lon: , lat: }, or an array of [, ]")};var Bl=2*Math.PI*6371008.8;function Vl(t){return Bl*Math.cos(t*Math.PI/180)}function Fl(t){return (180+t)/360}function Dl(t){return (180-180/Math.PI*Math.log(Math.tan(Math.PI/4+t*Math.PI/360)))/360}function Ll(t,e){return t/Vl(e)}function Rl(t){return 360/Math.PI*Math.atan(Math.exp((180-360*t)*Math.PI/180))-90}var Ol=function(t,e,r){void 0===r&&(r=0),this.x=+t,this.y=+e,this.z=+r;};Ol.fromLngLat=function(t,e){void 0===e&&(e=0);var r=Pl.convert(t);return new Ol(Fl(r.lng),Dl(r.lat),Ll(e,r.lat))},Ol.prototype.toLngLat=function(){return new Pl(360*this.x-180,Rl(this.y))},Ol.prototype.toAltitude=function(){return this.z*Vl(Rl(this.y))},Ol.prototype.meterInMercatorCoordinateUnits=function(){return 1/Bl*(t=Rl(this.y),1/Math.cos(t*Math.PI/180));var t;};var Ul=function(t,e,r){this.z=t,this.x=e,this.y=r,this.key=Nl(0,t,t,e,r);};Ul.prototype.equals=function(t){return this.z===t.z&&this.x===t.x&&this.y===t.y},Ul.prototype.url=function(t,e){var r,n,i,a,o,s=(n=this.y,i=this.z,a=El(256*(r=this.x),256*(n=Math.pow(2,i)-n-1),i),o=El(256*(r+1),256*(n+1),i),a[0]+","+a[1]+","+o[0]+","+o[1]),u=function(t,e,r){for(var n,i="",a=t;a>0;a--)i+=(e&(n=1<this.canonical.z?new ql(t,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y):new ql(t,this.wrap,t,this.canonical.x>>e,this.canonical.y>>e)},ql.prototype.calculateScaledKey=function(t,e){var r=this.canonical.z-t;return t>this.canonical.z?Nl(this.wrap*+e,t,this.canonical.z,this.canonical.x,this.canonical.y):Nl(this.wrap*+e,t,t,this.canonical.x>>r,this.canonical.y>>r)},ql.prototype.isChildOf=function(t){if(t.wrap!==this.wrap)return !1;var e=this.canonical.z-t.canonical.z;return 0===t.overscaledZ||t.overscaledZ>e&&t.canonical.y===this.canonical.y>>e},ql.prototype.children=function(t){if(this.overscaledZ>=t)return [new ql(this.overscaledZ+1,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)];var e=this.canonical.z+1,r=2*this.canonical.x,n=2*this.canonical.y;return [new ql(e,this.wrap,e,r,n),new ql(e,this.wrap,e,r+1,n),new ql(e,this.wrap,e,r,n+1),new ql(e,this.wrap,e,r+1,n+1)]},ql.prototype.isLessThan=function(t){return this.wrapt.wrap)&&(this.overscaledZt.overscaledZ)&&(this.canonical.xt.canonical.x)&&this.canonical.y=this.dim+1||e<-1||e>=this.dim+1)throw new RangeError("out of range source coordinates for DEM data");return (e+1)*this.stride+(t+1)},Kl.prototype._unpackMapbox=function(t,e,r){return (256*t*256+256*e+r)/10-1e4},Kl.prototype._unpackTerrarium=function(t,e,r){return 256*t+e+r/256-32768},Kl.prototype.getPixels=function(){return new fo({width:this.stride,height:this.stride},new Uint8Array(this.data.buffer))},Kl.prototype.backfillBorder=function(t,e,r){if(this.dim!==t.dim)throw new Error("dem dimension mismatch");var n=e*this.dim,i=e*this.dim+this.dim,a=r*this.dim,o=r*this.dim+this.dim;switch(e){case-1:n=i-1;break;case 1:i=n+1;}switch(r){case-1:a=o-1;break;case 1:o=a+1;}for(var s=-e*this.dim,u=-r*this.dim,l=a;l=0&&p[3]>=0&&s.insert(o,p[0],p[1],p[2],p[3]);}},Hl.prototype.loadVTLayers=function(){return this.vtLayers||(this.vtLayers=new ds.VectorTile(new Ks(this.rawTileData)).layers,this.sourceLayerCoder=new Gl(this.vtLayers?Object.keys(this.vtLayers).sort():["_geojsonTileLayer"])),this.vtLayers},Hl.prototype.query=function(t,e,r,n){var a=this;this.loadVTLayers();for(var o=t.params||{},s=8192/t.tileSize/t.scale,u=rn(o.filter),l=t.queryGeometry,p=t.queryPadding*s,c=$l(l),h=this.grid.query(c.minX-p,c.minY-p,c.maxX+p,c.maxY+p),f=$l(t.cameraQueryGeometry),y=this.grid3D.query(f.minX-p,f.minY-p,f.maxX+p,f.maxY+p,(function(e,r,n,a){return function(t,e,r,n,a){for(var o=0,s=t;o=u.x&&a>=u.y)return !0}var l=[new i(e,r),new i(e,a),new i(n,a),new i(n,r)];if(t.length>2)for(var p=0,c=l;p=0)return !0;return !1}(a,c)){var h=this.sourceLayerCoder.decode(r),f=this.vtLayers[h].feature(n);if(i.filter(new ii(this.tileID.overscaledZ),f))for(var y=this.getId(f,h),d=0;dn)i=!1;else if(e)if(this.expirationTimeot&&(t.getActor().send("enforceCacheSizeLimit",at),pt=0);},t.clamp=u,t.clearTileCache=function(t){var e=self.caches.delete("mapbox-tiles");t&&e.catch(t).then((function(){return t()}));},t.clipLine=Uu,t.clone=function(t){var e=new to(16);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],e},t.clone$1=x,t.clone$2=function(t){var e=new to(3);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e},t.collisionCircleLayout=Os,t.config=L,t.create=function(){var t=new to(16);return to!=Float32Array&&(t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0),t[0]=1,t[5]=1,t[10]=1,t[15]=1,t},t.create$1=function(){var t=new to(9);return to!=Float32Array&&(t[1]=0,t[2]=0,t[3]=0,t[5]=0,t[6]=0,t[7]=0),t[0]=1,t[4]=1,t[8]=1,t},t.create$2=function(){var t=new to(4);return to!=Float32Array&&(t[1]=0,t[2]=0),t[0]=1,t[3]=1,t},t.createCommonjsModule=e,t.createExpression=Nr,t.createLayout=Ai,t.createStyleLayer=function(t){return "custom"===t.type?new bl(t):new wl[t.type](t)},t.cross=function(t,e,r){var n=e[0],i=e[1],a=e[2],o=r[0],s=r[1],u=r[2];return t[0]=i*u-a*s,t[1]=a*o-n*u,t[2]=n*s-i*o,t},t.deepEqual=function t(e,r){if(Array.isArray(e)){if(!Array.isArray(r)||e.length!==r.length)return !1;for(var n=0;n0&&(a=1/Math.sqrt(a)),t[0]=e[0]*a,t[1]=e[1]*a,t[2]=e[2]*a,t},t.number=je,t.offscreenCanvasSupported=ct,t.ortho=function(t,e,r,n,i,a,o){var s=1/(e-r),u=1/(n-i),l=1/(a-o);return t[0]=-2*s,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=-2*u,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=2*l,t[11]=0,t[12]=(e+r)*s,t[13]=(i+n)*u,t[14]=(o+a)*l,t[15]=1,t},t.parseGlyphPBF=function(t){return new Ks(t).readFields(uu,[])},t.pbf=Ks,t.performSymbolLayout=function(t,e,r,n,i,a,o){t.createArrays(),t.tilePixelRatio=8192/(512*t.overscaling),t.compareText={},t.iconsNeedLinear=!1;var s=t.layers[0].layout,u=t.layers[0]._unevaluatedLayout._values,l={};if("composite"===t.textSizeData.kind){var p=t.textSizeData,c=p.maxZoom;l.compositeTextSizes=[u["text-size"].possiblyEvaluate(new ii(p.minZoom),o),u["text-size"].possiblyEvaluate(new ii(c),o)];}if("composite"===t.iconSizeData.kind){var h=t.iconSizeData,f=h.maxZoom;l.compositeIconSizes=[u["icon-size"].possiblyEvaluate(new ii(h.minZoom),o),u["icon-size"].possiblyEvaluate(new ii(f),o)];}l.layoutTextSize=u["text-size"].possiblyEvaluate(new ii(t.zoom+1),o),l.layoutIconSize=u["icon-size"].possiblyEvaluate(new ii(t.zoom+1),o),l.textMaxSize=u["text-size"].possiblyEvaluate(new ii(18));for(var y=24*s.get("text-line-height"),d="map"===s.get("text-rotation-alignment")&&"point"!==s.get("symbol-placement"),m=s.get("text-keep-upright"),v=s.get("text-size"),g=function(){var a=b[x],u=s.get("text-font").evaluate(a,{},o).join(","),p=v.evaluate(a,{},o),c=l.layoutTextSize.evaluate(a,{},o),h=l.layoutIconSize.evaluate(a,{},o),f={horizontal:{},vertical:void 0},g=a.text,_=[0,0];if(g){var A=g.toString(),S=24*s.get("text-letter-spacing").evaluate(a,{},o),k=function(t){for(var e=0,r=t;e=8192||c.y<0||c.y>=8192||function(t,e,r,n,i,a,o,s,u,l,p,c,h,f,y,d,m,v,g,x,b,_,A,S,k){var I,z,C,M,E,T=t.addToLineVertexArray(e,r),P=0,B=0,V=0,F=0,D=-1,L=-1,R={},O=la(""),U=0,j=0;if(void 0===s._unevaluatedLayout.getValue("text-radial-offset")?(U=(I=s.layout.get("text-offset").evaluate(b,{},S).map((function(t){return 24*t})))[0],j=I[1]):(U=24*s.layout.get("text-radial-offset").evaluate(b,{},S),j=Wu),t.allowVerticalPlacement&&n.vertical){var q=s.layout.get("text-rotate").evaluate(b,{},S)+90;M=new Zu(u,e,l,p,c,n.vertical,h,f,y,q),o&&(E=new Zu(u,e,l,p,c,o,m,v,y,q));}if(i){var N=s.layout.get("icon-rotate").evaluate(b,{}),K="none"!==s.layout.get("icon-text-fit"),G=ju(i,N,A,K),Z=o?ju(o,N,A,K):void 0;C=new Zu(u,e,l,p,c,i,m,v,!1,N),P=4*G.length;var X=t.iconSizeData,J=null;"source"===X.kind?(J=[128*s.layout.get("icon-size").evaluate(b,{})])[0]>32640&&w(t.layerIds[0]+': Value for "icon-size" is >= 255. Reduce your "icon-size".'):"composite"===X.kind&&((J=[128*_.compositeIconSizes[0].evaluate(b,{},S),128*_.compositeIconSizes[1].evaluate(b,{},S)])[0]>32640||J[1]>32640)&&w(t.layerIds[0]+': Value for "icon-size" is >= 255. Reduce your "icon-size".'),t.addSymbols(t.icon,G,J,x,g,b,!1,e,T.lineStartIndex,T.lineLength,-1,S),D=t.icon.placedSymbolArray.length-1,Z&&(B=4*Z.length,t.addSymbols(t.icon,Z,J,x,g,b,du.vertical,e,T.lineStartIndex,T.lineLength,-1,S),L=t.icon.placedSymbolArray.length-1);}for(var H in n.horizontal){var Y=n.horizontal[H];if(!z){O=la(Y.text);var $=s.layout.get("text-rotate").evaluate(b,{},S);z=new Zu(u,e,l,p,c,Y,h,f,y,$);}var W=1===Y.positionedLines.length;if(V+=el(t,e,Y,a,s,y,b,d,T,n.vertical?du.horizontal:du.horizontalOnly,W?Object.keys(n.horizontal):[H],R,D,_,S),W)break}n.vertical&&(F+=el(t,e,n.vertical,a,s,y,b,d,T,du.vertical,["vertical"],R,L,_,S));var Q=z?z.boxStartIndex:t.collisionBoxArray.length,tt=z?z.boxEndIndex:t.collisionBoxArray.length,et=M?M.boxStartIndex:t.collisionBoxArray.length,rt=M?M.boxEndIndex:t.collisionBoxArray.length,nt=C?C.boxStartIndex:t.collisionBoxArray.length,it=C?C.boxEndIndex:t.collisionBoxArray.length,at=E?E.boxStartIndex:t.collisionBoxArray.length,ot=E?E.boxEndIndex:t.collisionBoxArray.length,st=-1,ut=function(t,e){return t&&t.circleDiameter?Math.max(t.circleDiameter,e):e};st=ut(z,st),st=ut(M,st),st=ut(C,st);var lt=(st=ut(E,st))>-1?1:0;lt&&(st*=k/24),t.glyphOffsetArray.length>=cl.MAX_GLYPHS&&w("Too many glyphs being rendered in a tile. See https://github.com/mapbox/mapbox-gl-js/issues/2907"),void 0!==b.sortKey&&t.addToSortKeyRanges(t.symbolInstances.length,b.sortKey),t.symbolInstances.emplaceBack(e.x,e.y,R.right>=0?R.right:-1,R.center>=0?R.center:-1,R.left>=0?R.left:-1,R.vertical||-1,D,L,O,Q,tt,et,rt,nt,it,at,ot,l,V,F,P,B,lt,0,h,U,j,st);}(t,c,s,r,n,i,h,t.layers[0],t.collisionBoxArray,e.index,e.sourceLayerIndex,t.index,v,_,k,u,x,A,I,y,e,a,l,p,o);};if("line"===z)for(var T=0,P=Uu(e.geometry,0,0,8192,8192);T1){var U=Ru(O,S,r.vertical||d,n,24,g);U&&E(O,U);}}else if("Polygon"===e.type)for(var j=0,q=Wo(e.geometry,0);j=T.maxzoom||"none"!==T.visibility&&(s(P,this.zoom,i),(g[T.id]=T.createBucket({index:h.bucketLayerIDs.length,layers:P,zoom:this.zoom,pixelRatio:this.pixelRatio,overscaling:this.overscaling,collisionBoxArray:this.collisionBoxArray,sourceLayerIndex:w,sourceID:this.source})).populate(S,v,this.tileID.canonical),h.bucketLayerIDs.push(P.map((function(e){return e.id}))));}}}var C=e.mapObject(v.glyphDependencies,(function(e){return Object.keys(e).map(Number)}));Object.keys(C).length?n.send("getGlyphs",{uid:this.uid,stacks:C},(function(e,t){c||(c=e,p=t,O.call(l));})):p={};var D=Object.keys(v.iconDependencies);D.length?n.send("getImages",{icons:D,source:this.source,tileID:this.tileID,type:"icons"},(function(e,t){c||(c=e,f=t,O.call(l));})):f={};var L=Object.keys(v.patternDependencies);function O(){if(c)return a(c);if(p&&f&&d){var t=new o(p),r=new e.ImageAtlas(f,d);for(var n in g){var l=g[n];l instanceof e.SymbolBucket?(s(l.layers,this.zoom,i),e.performSymbolLayout(l,p,t.positions,f,r.iconPositions,this.showCollisionBoxes,this.tileID.canonical)):l.hasPattern&&(l instanceof e.LineBucket||l instanceof e.FillBucket||l instanceof e.FillExtrusionBucket)&&(s(l.layers,this.zoom,i),l.addFeatures(v,this.tileID.canonical,r.patternPositions));}this.status="done",a(null,{buckets:e.values(g).filter((function(e){return !e.isEmpty()})),featureIndex:h,collisionBoxArray:this.collisionBoxArray,glyphAtlasImage:t.image,imageAtlas:r,glyphMap:this.returnDependencies?p:null,iconMap:this.returnDependencies?f:null,glyphPositions:this.returnDependencies?t.positions:null});}}L.length?n.send("getImages",{icons:L,source:this.source,tileID:this.tileID,type:"patterns"},(function(e,t){c||(c=e,d=t,O.call(l));})):d={},O.call(this);};var l=function(e,t,r,i){this.actor=e,this.layerIndex=t,this.availableImages=r,this.loadVectorData=i||a,this.loading={},this.loaded={};};l.prototype.loadTile=function(t,r){var i=this,o=t.uid;this.loading||(this.loading={});var s=!!(t&&t.request&&t.request.collectResourceTiming)&&new e.RequestPerformance(t.request),a=this.loading[o]=new n(t);a.abort=this.loadVectorData(t,(function(t,n){if(delete i.loading[o],t||!n)return a.status="done",i.loaded[o]=a,r(t);var l=n.rawData,u={};n.expires&&(u.expires=n.expires),n.cacheControl&&(u.cacheControl=n.cacheControl);var h={};if(s){var c=s.finish();c&&(h.resourceTiming=JSON.parse(JSON.stringify(c)));}a.vectorTile=n.vectorTile,a.parse(n.vectorTile,i.layerIndex,i.availableImages,i.actor,(function(t,i){if(t||!i)return r(t);r(null,e.extend({rawTileData:l.slice(0)},i,u,h));})),i.loaded=i.loaded||{},i.loaded[o]=a;}));},l.prototype.reloadTile=function(e,t){var r=this,i=this.loaded,o=e.uid,n=this;if(i&&i[o]){var s=i[o];s.showCollisionBoxes=e.showCollisionBoxes;var a=function(e,i){var o=s.reloadCallback;o&&(delete s.reloadCallback,s.parse(s.vectorTile,n.layerIndex,r.availableImages,n.actor,o)),t(e,i);};"parsing"===s.status?s.reloadCallback=a:"done"===s.status&&(s.vectorTile?s.parse(s.vectorTile,this.layerIndex,this.availableImages,this.actor,a):a());}},l.prototype.abortTile=function(e,t){var r=this.loading,i=e.uid;r&&r[i]&&r[i].abort&&(r[i].abort(),delete r[i]),t();},l.prototype.removeTile=function(e,t){var r=this.loaded,i=e.uid;r&&r[i]&&delete r[i],t();};var u=e.window.ImageBitmap,h=function(){this.loaded={};};function c(e,t){if(0!==e.length){p(e[0],t);for(var r=1;r=0!=!!t&&e.reverse();}h.prototype.loadTile=function(t,r){var i=t.uid,o=t.encoding,n=t.rawImageData,s=u&&n instanceof u?this.getImageData(n):n,a=new e.DEMData(i,s,o);this.loaded=this.loaded||{},this.loaded[i]=a,r(null,a);},h.prototype.getImageData=function(t){this.offscreenCanvas&&this.offscreenCanvasContext||(this.offscreenCanvas=new OffscreenCanvas(t.width,t.height),this.offscreenCanvasContext=this.offscreenCanvas.getContext("2d")),this.offscreenCanvas.width=t.width,this.offscreenCanvas.height=t.height,this.offscreenCanvasContext.drawImage(t,0,0,t.width,t.height);var r=this.offscreenCanvasContext.getImageData(-1,-1,t.width+2,t.height+2);return this.offscreenCanvasContext.clearRect(0,0,this.offscreenCanvas.width,this.offscreenCanvas.height),new e.RGBAImage({width:r.width,height:r.height},r.data)},h.prototype.removeTile=function(e){var t=this.loaded,r=e.uid;t&&t[r]&&delete t[r];};var f=e.vectorTile.VectorTileFeature.prototype.toGeoJSON,d=function(t){this._feature=t,this.extent=e.EXTENT,this.type=t.type,this.properties=t.tags,"id"in t&&!isNaN(t.id)&&(this.id=parseInt(t.id,10));};d.prototype.loadGeometry=function(){if(1===this._feature.type){for(var t=[],r=0,i=this._feature.geometry;r>31}function T(e,t){for(var r=e.loadGeometry(),i=e.type,o=0,n=0,s=r.length,a=0;a>1;!function e(t,r,i,o,n,s){for(;n>o;){if(n-o>600){var a=n-o+1,l=i-o+1,u=Math.log(a),h=.5*Math.exp(2*u/3),c=.5*Math.sqrt(u*h*(a-h)/a)*(l-a/2<0?-1:1);e(t,r,i,Math.max(o,Math.floor(i-l*h/a+c)),Math.min(n,Math.floor(i+(a-l)*h/a+c)),s);}var p=r[2*i+s],f=o,d=n;for(D(t,r,o,i),r[2*n+s]>p&&D(t,r,o,n);fp;)d--;}r[2*o+s]===p?D(t,r,o,d):D(t,r,++d,n),d<=i&&(o=d+1),i<=d&&(n=d-1);}}(t,r,a,o,n,s%2),e(t,r,i,o,a-1,s+1),e(t,r,i,a+1,n,s+1);}}(s,a,i,0,s.length-1,0);};F.prototype.range=function(e,t,r,i){return function(e,t,r,i,o,n,s){for(var a,l,u=[0,e.length-1,0],h=[];u.length;){var c=u.pop(),p=u.pop(),f=u.pop();if(p-f<=s)for(var d=f;d<=p;d++)l=t[2*d+1],(a=t[2*d])>=r&&a<=o&&l>=i&&l<=n&&h.push(e[d]);else {var g=Math.floor((f+p)/2);l=t[2*g+1],(a=t[2*g])>=r&&a<=o&&l>=i&&l<=n&&h.push(e[g]);var v=(c+1)%2;(0===c?r<=a:i<=l)&&(u.push(f),u.push(g-1),u.push(v)),(0===c?o>=a:n>=l)&&(u.push(g+1),u.push(p),u.push(v));}}return h}(this.ids,this.coords,e,t,r,i,this.nodeSize)},F.prototype.within=function(e,t,r){return function(e,t,r,i,o,n){for(var s=[0,e.length-1,0],a=[],l=o*o;s.length;){var u=s.pop(),h=s.pop(),c=s.pop();if(h-c<=n)for(var p=c;p<=h;p++)O(t[2*p],t[2*p+1],r,i)<=l&&a.push(e[p]);else {var f=Math.floor((c+h)/2),d=t[2*f],g=t[2*f+1];O(d,g,r,i)<=l&&a.push(e[f]);var v=(u+1)%2;(0===u?r-o<=d:i-o<=g)&&(s.push(c),s.push(f-1),s.push(v)),(0===u?r+o>=d:i+o>=g)&&(s.push(f+1),s.push(h),s.push(v));}}return a}(this.ids,this.coords,e,t,r,this.nodeSize)};var N={minZoom:0,maxZoom:16,radius:40,extent:512,nodeSize:64,log:!1,generateId:!1,reduce:null,map:function(e){return e}},J=function(e){this.options=V(Object.create(N),e),this.trees=new Array(this.options.maxZoom+1);};function Z(e,t,r,i,o){return {x:e,y:t,zoom:1/0,id:r,parentId:-1,numPoints:i,properties:o}}function A(e,t){var r=e.geometry.coordinates,i=r[1];return {x:Y(r[0]),y:j(i),zoom:1/0,index:t,parentId:-1}}function B(e){return {type:"Feature",id:e.id,properties:G(e),geometry:{type:"Point",coordinates:[(i=e.x,360*(i-.5)),(t=e.y,r=(180-360*t)*Math.PI/180,360*Math.atan(Math.exp(r))/Math.PI-90)]}};var t,r,i;}function G(e){var t=e.numPoints,r=t>=1e4?Math.round(t/1e3)+"k":t>=1e3?Math.round(t/100)/10+"k":t;return V(V({},e.properties),{cluster:!0,cluster_id:e.id,point_count:t,point_count_abbreviated:r})}function Y(e){return e/360+.5}function j(e){var t=Math.sin(e*Math.PI/180),r=.5-.25*Math.log((1+t)/(1-t))/Math.PI;return r<0?0:r>1?1:r}function V(e,t){for(var r in t)e[r]=t[r];return e}function X(e){return e.x}function W(e){return e.y}function R(e,t,r,i,o,n){var s=o-r,a=n-i;if(0!==s||0!==a){var l=((e-r)*s+(t-i)*a)/(s*s+a*a);l>1?(r=o,i=n):l>0&&(r+=s*l,i+=a*l);}return (s=e-r)*s+(a=t-i)*a}function q(e,t,r,i){var o={id:void 0===e?null:e,type:t,geometry:r,tags:i,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0};return function(e){var t=e.geometry,r=e.type;if("Point"===r||"MultiPoint"===r||"LineString"===r)U(e,t);else if("Polygon"===r||"MultiLineString"===r)for(var i=0;i0&&(s+=i?(o*u-l*n)/2:Math.sqrt(Math.pow(l-o,2)+Math.pow(u-n,2))),o=l,n=u;}var h=t.length-3;t[2]=1,function e(t,r,i,o){for(var n,s=o,a=i-r>>1,l=i-r,u=t[r],h=t[r+1],c=t[i],p=t[i+1],f=r+3;fs)n=f,s=d;else if(d===s){var g=Math.abs(f-a);go&&(n-r>3&&e(t,r,n,o),t[n+2]=s,i-n>3&&e(t,n,i,o));}(t,0,h,r),t[h+2]=1,t.size=Math.abs(s),t.start=0,t.end=t.size;}function Q(e,t,r,i){for(var o=0;o1?1:r}function re(e,t,r,i,o,n,s,a){if(i/=t,n>=(r/=t)&&s=i)return null;for(var l=[],u=0;u=r&&d=i)){var g=[];if("Point"===p||"MultiPoint"===p)ie(c,g,r,i,o);else if("LineString"===p)oe(c,g,r,i,o,!1,a.lineMetrics);else if("MultiLineString"===p)se(c,g,r,i,o,!1);else if("Polygon"===p)se(c,g,r,i,o,!0);else if("MultiPolygon"===p)for(var v=0;v=r&&s<=i&&(t.push(e[n]),t.push(e[n+1]),t.push(e[n+2]));}}function oe(e,t,r,i,o,n,s){for(var a,l,u=ne(e),h=0===o?le:ue,c=e.start,p=0;pr&&(l=h(u,f,d,v,m,r),s&&(u.start=c+a*l)):y>i?x=r&&(l=h(u,f,d,v,m,r),w=!0),x>i&&y<=i&&(l=h(u,f,d,v,m,i),w=!0),!n&&w&&(s&&(u.end=c+a*l),t.push(u),u=ne(e)),s&&(c+=a);}var S=e.length-3;f=e[S],d=e[S+1],g=e[S+2],(y=0===o?f:d)>=r&&y<=i&&ae(u,f,d,g),S=u.length-3,n&&S>=3&&(u[S]!==u[0]||u[S+1]!==u[1])&&ae(u,u[0],u[1],u[2]),u.length&&t.push(u);}function ne(e){var t=[];return t.size=e.size,t.start=e.start,t.end=e.end,t}function se(e,t,r,i,o,n){for(var s=0;ss.maxX&&(s.maxX=h),c>s.maxY&&(s.maxY=c);}return s}function ge(e,t,r,i){var o=t.geometry,n=t.type,s=[];if("Point"===n||"MultiPoint"===n)for(var a=0;a0&&t.size<(o?s:i))r.numPoints+=t.length/3;else {for(var a=[],l=0;ls)&&(r.numSimplified++,a.push(t[l]),a.push(t[l+1])),r.numPoints++;o&&function(e,t){for(var r=0,i=0,o=e.length,n=o-2;i0===t)for(i=0,o=e.length;i24)throw new Error("maxZoom should be in the 0-24 range");if(t.promoteId&&t.generateId)throw new Error("promoteId and generateId cannot be used together.");var i=function(e,t){var r=[];if("FeatureCollection"===e.type)for(var i=0;i=i;u--){var h=+Date.now();a=this._cluster(a,u),this.trees[u]=new F(a,X,W,n,Float32Array),r&&console.log("z%d: %d clusters in %dms",u,a.length,+Date.now()-h);}return r&&console.timeEnd("total time"),this},J.prototype.getClusters=function(e,t){var r=((e[0]+180)%360+360)%360-180,i=Math.max(-90,Math.min(90,e[1])),o=180===e[2]?180:((e[2]+180)%360+360)%360-180,n=Math.max(-90,Math.min(90,e[3]));if(e[2]-e[0]>=360)r=-180,o=180;else if(r>o){var s=this.getClusters([r,i,180,n],t),a=this.getClusters([-180,i,o,n],t);return s.concat(a)}for(var l=this.trees[this._limitZoom(t)],u=[],h=0,c=l.range(Y(r),j(n),Y(o),j(i));h1?this._map(a,!0):null,d=(s<<5)+(t+1)+this.points.length,g=0,v=u;g>5},J.prototype._getOriginZoom=function(e){return (e-this.points.length)%32},J.prototype._map=function(e,t){if(e.numPoints)return t?V({},e.properties):e.properties;var r=this.points[e.index].properties,i=this.options.map(r);return t&&i===r?V({},i):i},me.prototype.options={maxZoom:14,indexMaxZoom:5,indexMaxPoints:1e5,tolerance:3,extent:4096,buffer:64,lineMetrics:!1,promoteId:null,generateId:!1,debug:0},me.prototype.splitTile=function(e,t,r,i,o,n,s){for(var a=[e,t,r,i],l=this.options,u=l.debug;a.length;){i=a.pop(),r=a.pop(),t=a.pop(),e=a.pop();var h=1<1&&console.time("creation"),p=this.tiles[c]=de(e,t,r,i,l),this.tileCoords.push({z:t,x:r,y:i}),u)){u>1&&(console.log("tile z%d-%d-%d (features: %d, points: %d, simplified: %d)",t,r,i,p.numFeatures,p.numPoints,p.numSimplified),console.timeEnd("creation"));var f="z"+t;this.stats[f]=(this.stats[f]||0)+1,this.total++;}if(p.source=e,o){if(t===l.maxZoom||t===o)continue;var d=1<1&&console.time("clipping");var g,v,m,y,x,w,S=.5*l.buffer/l.extent,I=.5-S,M=.5+S,b=1+S;g=v=m=y=null,x=re(e,h,r-S,r+M,0,p.minX,p.maxX,l),w=re(e,h,r+I,r+b,0,p.minX,p.maxX,l),e=null,x&&(g=re(x,h,i-S,i+M,1,p.minY,p.maxY,l),v=re(x,h,i+I,i+b,1,p.minY,p.maxY,l),x=null),w&&(m=re(w,h,i-S,i+M,1,p.minY,p.maxY,l),y=re(w,h,i+I,i+b,1,p.minY,p.maxY,l),w=null),u>1&&console.timeEnd("clipping"),a.push(g||[],t+1,2*r,2*i),a.push(v||[],t+1,2*r,2*i+1),a.push(m||[],t+1,2*r+1,2*i),a.push(y||[],t+1,2*r+1,2*i+1);}}},me.prototype.getTile=function(e,t,r){var i=this.options,o=i.extent,n=i.debug;if(e<0||e>24)return null;var s=1<1&&console.log("drilling down to z%d-%d-%d",e,t,r);for(var l,u=e,h=t,c=r;!l&&u>0;)u--,h=Math.floor(h/2),c=Math.floor(c/2),l=this.tiles[ye(u,h,c)];return l&&l.source?(n>1&&console.log("found parent tile z%d-%d-%d",u,h,c),n>1&&console.time("drilling down"),this.splitTile(l.source,u,h,c,e,t,r),n>1&&console.timeEnd("drilling down"),this.tiles[a]?pe(this.tiles[a],o):null):null};var we=function(t){function r(e,r,i,o){t.call(this,e,r,i,xe),o&&(this.loadGeoJSON=o);}return t&&(r.__proto__=t),(r.prototype=Object.create(t&&t.prototype)).constructor=r,r.prototype.loadData=function(e,t){this._pendingCallback&&this._pendingCallback(null,{abandoned:!0}),this._pendingCallback=t,this._pendingLoadDataParams=e,this._state&&"Idle"!==this._state?this._state="NeedsLoadData":(this._state="Coalescing",this._loadData());},r.prototype._loadData=function(){var t=this;if(this._pendingCallback&&this._pendingLoadDataParams){var r=this._pendingCallback,i=this._pendingLoadDataParams;delete this._pendingCallback,delete this._pendingLoadDataParams;var o=!!(i&&i.request&&i.request.collectResourceTiming)&&new e.RequestPerformance(i.request);this.loadGeoJSON(i,(function(n,s){if(n||!s)return r(n);if("object"!=typeof s)return r(new Error("Input data given to '"+i.source+"' is not a valid GeoJSON object."));!function e(t,r){var i,o=t&&t.type;if("FeatureCollection"===o)for(i=0;i=0?0:e.button},i.remove=function(t){t.parentNode&&t.parentNode.removeChild(t);};var p=function(e){function i(){e.call(this),this.images={},this.updatedImages={},this.callbackDispatchedThisFrame={},this.loaded=!1,this.requestors=[],this.patterns={},this.atlasImage=new t.RGBAImage({width:1,height:1}),this.dirty=!0;}return e&&(i.__proto__=e),(i.prototype=Object.create(e&&e.prototype)).constructor=i,i.prototype.isLoaded=function(){return this.loaded},i.prototype.setLoaded=function(t){if(this.loaded!==t&&(this.loaded=t,t)){for(var e=0,i=this.requestors;e=0?1.2:1));}function g(t,e,i,o,r,a,n){for(var s=0;s65535)e(new Error("glyphs > 65535 not supported"));else if(a.ranges[s])e(null,{stack:i,id:r,glyph:n});else {var l=a.requests[s];l||(l=a.requests[s]=[],y.loadGlyphRange(i,s,o.url,o.requestManager,(function(t,e){if(e){for(var i in e)o._doesCharSupportLocalGlyph(+i)||(a.glyphs[+i]=e[+i]);a.ranges[s]=!0;}for(var r=0,n=l;r1&&(s=t[++n]);var c=Math.abs(l-s.left),u=Math.abs(l-s.right),h=Math.min(c,u),p=void 0,d=r/i*(o+1);if(s.isDash){var _=o-Math.abs(d);p=Math.sqrt(h*h+_*_);}else p=o-Math.sqrt(h*h+d*d);this.data[a+l]=Math.max(0,Math.min(255,p+128));}},T.prototype.addRegularDash=function(t){for(var e=t.length-1;e>=0;--e){var i=t[e],o=t[e+1];i.zeroLength?t.splice(e,1):o&&o.isDash===i.isDash&&(o.left=i.left,t.splice(e,1));}var r=t[0],a=t[t.length-1];r.isDash===a.isDash&&(r.left=a.left-this.width,a.right=r.right+this.width);for(var n=this.width*this.nextRow,s=0,l=t[s],c=0;c1&&(l=t[++s]);var u=Math.abs(c-l.left),h=Math.abs(c-l.right),p=Math.min(u,h);this.data[n+c]=Math.max(0,Math.min(255,(l.isDash?p:-p)+128));}},T.prototype.addDash=function(e,i){var o=i?7:0,r=2*o+1;if(this.nextRow+r>this.height)return t.warnOnce("LineAtlas out of space"),null;for(var a=0,n=0;n=o&&e.x=r&&e.y0&&(l[new t.OverscaledTileID(e.overscaledZ,a,i.z,r,i.y-1).key]={backfilled:!1},l[new t.OverscaledTileID(e.overscaledZ,e.wrap,i.z,i.x,i.y-1).key]={backfilled:!1},l[new t.OverscaledTileID(e.overscaledZ,s,i.z,n,i.y-1).key]={backfilled:!1}),i.y+10&&(o.resourceTiming=e._resourceTiming,e._resourceTiming=[]),e.fire(new t.Event("data",o));}}));},i.prototype.onAdd=function(t){this.map=t,this.load();},i.prototype.setData=function(e){var i=this;return this._data=e,this.fire(new t.Event("dataloading",{dataType:"source"})),this._updateWorkerData((function(e){if(e)i.fire(new t.ErrorEvent(e));else {var o={dataType:"source",sourceDataType:"content"};i._collectResourceTiming&&i._resourceTiming&&i._resourceTiming.length>0&&(o.resourceTiming=i._resourceTiming,i._resourceTiming=[]),i.fire(new t.Event("data",o));}})),this},i.prototype.getClusterExpansionZoom=function(t,e){return this.actor.send("geojson.getClusterExpansionZoom",{clusterId:t,source:this.id},e),this},i.prototype.getClusterChildren=function(t,e){return this.actor.send("geojson.getClusterChildren",{clusterId:t,source:this.id},e),this},i.prototype.getClusterLeaves=function(t,e,i,o){return this.actor.send("geojson.getClusterLeaves",{source:this.id,clusterId:t,limit:e,offset:i},o),this},i.prototype._updateWorkerData=function(e){var i=this;this._loaded=!1;var o=t.extend({},this.workerOptions),r=this._data;"string"==typeof r?(o.request=this.map._requestManager.transformRequest(t.browser.resolveURL(r),t.ResourceType.Source),o.request.collectResourceTiming=this._collectResourceTiming):o.data=JSON.stringify(r),this.actor.send(this.type+".loadData",o,(function(t,r){i._removed||r&&r.abandoned||(i._loaded=!0,r&&r.resourceTiming&&r.resourceTiming[i.id]&&(i._resourceTiming=r.resourceTiming[i.id].slice(0)),i.actor.send(i.type+".coalesce",{source:o.source},null),e(t));}));},i.prototype.loaded=function(){return this._loaded},i.prototype.loadTile=function(e,i){var o=this,r=e.actor?"reloadTile":"loadTile";e.actor=this.actor,e.request=this.actor.send(r,{type:this.type,uid:e.uid,tileID:e.tileID,zoom:e.tileID.overscaledZ,maxZoom:this.maxzoom,tileSize:this.tileSize,source:this.id,pixelRatio:t.browser.devicePixelRatio,showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId},(function(t,a){return delete e.request,e.unloadVectorData(),e.aborted?i(null):t?i(t):(e.loadVectorData(a,o.map.painter,"reloadTile"===r),i(null))}));},i.prototype.abortTile=function(t){t.request&&(t.request.cancel(),delete t.request),t.aborted=!0;},i.prototype.unloadTile=function(t){t.unloadVectorData(),this.actor.send("removeTile",{uid:t.uid,type:this.type,source:this.id});},i.prototype.onRemove=function(){this._removed=!0,this.actor.send("removeSource",{type:this.type,source:this.id});},i.prototype.serialize=function(){return t.extend({},this._options,{type:this.type,data:this._data})},i.prototype.hasTransition=function(){return !1},i}(t.Evented),M=t.createLayout([{name:"a_pos",type:"Int16",components:2},{name:"a_texture_pos",type:"Int16",components:2}]),L=function(e){function i(t,i,o,r){e.call(this),this.id=t,this.dispatcher=o,this.coordinates=i.coordinates,this.type="image",this.minzoom=0,this.maxzoom=22,this.tileSize=512,this.tiles={},this._loaded=!1,this.setEventedParent(r),this.options=i;}return e&&(i.__proto__=e),(i.prototype=Object.create(e&&e.prototype)).constructor=i,i.prototype.load=function(e,i){var o=this;this._loaded=!1,this.fire(new t.Event("dataloading",{dataType:"source"})),this.url=this.options.url,t.getImage(this.map._requestManager.transformRequest(this.url,t.ResourceType.Image),(function(r,a){o._loaded=!0,r?o.fire(new t.ErrorEvent(r)):a&&(o.image=a,e&&(o.coordinates=e),i&&i(),o._finishLoading());}));},i.prototype.loaded=function(){return this._loaded},i.prototype.updateImage=function(t){var e=this;return this.image&&t.url?(this.options.url=t.url,this.load(t.coordinates,(function(){e.texture=null;})),this):this},i.prototype._finishLoading=function(){this.map&&(this.setCoordinates(this.coordinates),this.fire(new t.Event("data",{dataType:"source",sourceDataType:"metadata"})));},i.prototype.onAdd=function(t){this.map=t,this.load();},i.prototype.setCoordinates=function(e){var i=this;this.coordinates=e;var o=e.map(t.MercatorCoordinate.fromLngLat);this.tileID=function(e){for(var i=1/0,o=1/0,r=-1/0,a=-1/0,n=0,s=e;ni.end(0)?this.fire(new t.ErrorEvent(new t.ValidationError("sources."+this.id,null,"Playback for this video can be set only between the "+i.start(0)+" and "+i.end(0)+"-second mark."))):this.video.currentTime=e;}},i.prototype.getVideo=function(){return this.video},i.prototype.onAdd=function(t){this.map||(this.map=t,this.load(),this.video&&(this.video.play(),this.setCoordinates(this.coordinates)));},i.prototype.prepare=function(){if(!(0===Object.keys(this.tiles).length||this.video.readyState<2)){var e=this.map.painter.context,i=e.gl;for(var o in this.boundsBuffer||(this.boundsBuffer=e.createVertexBuffer(this._boundsArray,M.members)),this.boundsSegments||(this.boundsSegments=t.SegmentVector.simpleSegment(0,0,4,2)),this.texture?this.video.paused||(this.texture.bind(i.LINEAR,i.CLAMP_TO_EDGE),i.texSubImage2D(i.TEXTURE_2D,0,0,0,i.RGBA,i.UNSIGNED_BYTE,this.video)):(this.texture=new t.Texture(e,this.video,i.RGBA),this.texture.bind(i.LINEAR,i.CLAMP_TO_EDGE)),this.tiles){var r=this.tiles[o];"loaded"!==r.state&&(r.state="loaded",r.texture=this.texture);}}},i.prototype.serialize=function(){return {type:"video",urls:this.urls,coordinates:this.coordinates}},i.prototype.hasTransition=function(){return this.video&&!this.video.paused},i}(L),R=function(e){function i(i,o,r,a){e.call(this,i,o,r,a),o.coordinates?Array.isArray(o.coordinates)&&4===o.coordinates.length&&!o.coordinates.some((function(t){return !Array.isArray(t)||2!==t.length||t.some((function(t){return "number"!=typeof t}))}))||this.fire(new t.ErrorEvent(new t.ValidationError("sources."+i,null,'"coordinates" property must be an array of 4 longitude/latitude array pairs'))):this.fire(new t.ErrorEvent(new t.ValidationError("sources."+i,null,'missing required property "coordinates"'))),o.animate&&"boolean"!=typeof o.animate&&this.fire(new t.ErrorEvent(new t.ValidationError("sources."+i,null,'optional "animate" property must be a boolean value'))),o.canvas?"string"==typeof o.canvas||o.canvas instanceof t.window.HTMLCanvasElement||this.fire(new t.ErrorEvent(new t.ValidationError("sources."+i,null,'"canvas" must be either a string representing the ID of the canvas element from which to read, or an HTMLCanvasElement instance'))):this.fire(new t.ErrorEvent(new t.ValidationError("sources."+i,null,'missing required property "canvas"'))),this.options=o,this.animate=void 0===o.animate||o.animate;}return e&&(i.__proto__=e),(i.prototype=Object.create(e&&e.prototype)).constructor=i,i.prototype.load=function(){this._loaded=!0,this.canvas||(this.canvas=this.options.canvas instanceof t.window.HTMLCanvasElement?this.options.canvas:t.window.document.getElementById(this.options.canvas)),this.width=this.canvas.width,this.height=this.canvas.height,this._hasInvalidDimensions()?this.fire(new t.ErrorEvent(new Error("Canvas dimensions cannot be less than or equal to zero."))):(this.play=function(){this._playing=!0,this.map.triggerRepaint();},this.pause=function(){this._playing&&(this.prepare(),this._playing=!1);},this._finishLoading());},i.prototype.getCanvas=function(){return this.canvas},i.prototype.onAdd=function(t){this.map=t,this.load(),this.canvas&&this.animate&&this.play();},i.prototype.onRemove=function(){this.pause();},i.prototype.prepare=function(){var e=!1;if(this.canvas.width!==this.width&&(this.width=this.canvas.width,e=!0),this.canvas.height!==this.height&&(this.height=this.canvas.height,e=!0),!this._hasInvalidDimensions()&&0!==Object.keys(this.tiles).length){var i=this.map.painter.context,o=i.gl;for(var r in this.boundsBuffer||(this.boundsBuffer=i.createVertexBuffer(this._boundsArray,M.members)),this.boundsSegments||(this.boundsSegments=t.SegmentVector.simpleSegment(0,0,4,2)),this.texture?(e||this._playing)&&this.texture.update(this.canvas,{premultiply:!0}):this.texture=new t.Texture(i,this.canvas,o.RGBA,{premultiply:!0}),this.tiles){var a=this.tiles[r];"loaded"!==a.state&&(a.state="loaded",a.texture=this.texture);}}},i.prototype.serialize=function(){return {type:"canvas",coordinates:this.coordinates}},i.prototype.hasTransition=function(){return this._playing},i.prototype._hasInvalidDimensions=function(){for(var t=0,e=[this.canvas.width,this.canvas.height];tthis.max){var n=this._getAndRemoveByKey(this.order[0]);n&&this.onRemove(n);}return this},U.prototype.has=function(t){return t.wrapped().key in this.data},U.prototype.getAndRemove=function(t){return this.has(t)?this._getAndRemoveByKey(t.wrapped().key):null},U.prototype._getAndRemoveByKey=function(t){var e=this.data[t].shift();return e.timeout&&clearTimeout(e.timeout),0===this.data[t].length&&delete this.data[t],this.order.splice(this.order.indexOf(t),1),e.value},U.prototype.getByKey=function(t){var e=this.data[t];return e?e[0].value:null},U.prototype.get=function(t){return this.has(t)?this.data[t.wrapped().key][0].value:null},U.prototype.remove=function(t,e){if(!this.has(t))return this;var i=t.wrapped().key,o=void 0===e?0:this.data[i].indexOf(e),r=this.data[i][o];return this.data[i].splice(o,1),r.timeout&&clearTimeout(r.timeout),0===this.data[i].length&&delete this.data[i],this.onRemove(r.value),this.order.splice(this.order.indexOf(i),1),this},U.prototype.setMaxSize=function(t){for(this.max=t;this.order.length>this.max;){var e=this._getAndRemoveByKey(this.order[0]);e&&this.onRemove(e);}return this},U.prototype.filter=function(t){var e=[];for(var i in this.data)for(var o=0,r=this.data[i];o1||(Math.abs(i)>1&&(1===Math.abs(i+r)?i+=r:1===Math.abs(i-r)&&(i-=r)),e.dem&&t.dem&&(t.dem.backfillBorder(e.dem,i,o),t.neighboringTiles&&t.neighboringTiles[a]&&(t.neighboringTiles[a].backfilled=!0)));}},i.prototype.getTile=function(t){return this.getTileByID(t.key)},i.prototype.getTileByID=function(t){return this._tiles[t]},i.prototype._retainLoadedChildren=function(t,e,i,o){for(var r in this._tiles){var a=this._tiles[r];if(!(o[r]||!a.hasData()||a.tileID.overscaledZ<=e||a.tileID.overscaledZ>i)){for(var n=a.tileID;a&&a.tileID.overscaledZ>e+1;){var s=a.tileID.scaledTo(a.tileID.overscaledZ-1);(a=this._tiles[s.key])&&a.hasData()&&(n=s);}for(var l=n;l.overscaledZ>e;)if(t[(l=l.scaledTo(l.overscaledZ-1)).key]){o[n.key]=n;break}}}},i.prototype.findLoadedParent=function(t,e){if(t.key in this._loadedParentTiles){var i=this._loadedParentTiles[t.key];return i&&i.tileID.overscaledZ>=e?i:null}for(var o=t.overscaledZ-1;o>=e;o--){var r=t.scaledTo(o),a=this._getLoadedTile(r);if(a)return a}},i.prototype._getLoadedTile=function(t){var e=this._tiles[t.key];return e&&e.hasData()?e:this._cache.getByKey(t.wrapped().key)},i.prototype.updateCacheSize=function(t){var e=Math.ceil(t.width/this._source.tileSize)+1,i=Math.ceil(t.height/this._source.tileSize)+1,o=Math.floor(e*i*5),r="number"==typeof this._maxTileCacheSize?Math.min(this._maxTileCacheSize,o):o;this._cache.setMaxSize(r);},i.prototype.handleWrapJump=function(t){var e=Math.round((t-(void 0===this._prevLng?t:this._prevLng))/360);if(this._prevLng=t,e){var i={};for(var o in this._tiles){var r=this._tiles[o];r.tileID=r.tileID.unwrapTo(r.tileID.wrap+e),i[r.tileID.key]=r;}for(var a in this._tiles=i,this._timers)clearTimeout(this._timers[a]),delete this._timers[a];for(var n in this._tiles)this._setTileReloadTimer(n,this._tiles[n]);}},i.prototype.update=function(e){var o=this;if(this.transform=e,this._sourceLoaded&&!this._paused){var r;this.updateCacheSize(e),this.handleWrapJump(this.transform.center.lng),this._coveredTiles={},this.used?this._source.tileID?r=e.getVisibleUnwrappedCoordinates(this._source.tileID).map((function(e){return new t.OverscaledTileID(e.canonical.z,e.wrap,e.canonical.z,e.canonical.x,e.canonical.y)})):(r=e.coveringTiles({tileSize:this._source.tileSize,minzoom:this._source.minzoom,maxzoom:this._source.maxzoom,roundZoom:this._source.roundZoom,reparseOverscaled:this._source.reparseOverscaled}),this._source.hasTile&&(r=r.filter((function(t){return o._source.hasTile(t)})))):r=[];var a=e.coveringZoomLevel(this._source),n=Math.max(a-i.maxOverzooming,this._source.minzoom),s=Math.max(a+i.maxUnderzooming,this._source.minzoom),l=this._updateRetainedTiles(r,a);if(Lt(this._source.type)){for(var c={},u={},h=0,p=Object.keys(l);hthis._source.maxzoom){var m=_.children(this._source.maxzoom)[0],g=this.getTile(m);if(g&&g.hasData()){o[m.key]=m;continue}}else {var v=_.children(this._source.maxzoom);if(o[v[0].key]&&o[v[1].key]&&o[v[2].key]&&o[v[3].key])continue}for(var y=f.wasRequested(),x=_.overscaledZ-1;x>=a;--x){var b=_.scaledTo(x);if(r[b.key])break;if(r[b.key]=!0,!(f=this.getTile(b))&&y&&(f=this._addTile(b)),f&&(o[b.key]=b,y=f.wasRequested(),f.hasData()))break}}}return o},i.prototype._updateLoadedParentTileCache=function(){for(var t in this._loadedParentTiles={},this._tiles){for(var e=[],i=void 0,o=this._tiles[t].tileID;o.overscaledZ>0;){if(o.key in this._loadedParentTiles){i=this._loadedParentTiles[o.key];break}e.push(o.key);var r=o.scaledTo(o.overscaledZ-1);if(i=this._getLoadedTile(r))break;o=r;}for(var a=0,n=e;a0||(e.hasData()&&"reloading"!==e.state?this._cache.add(e.tileID,e,e.getExpiryTimeout()):(e.aborted=!0,this._abortTile(e),this._unloadTile(e))));},i.prototype.clearTiles=function(){for(var t in this._shouldReloadOnResume=!1,this._paused=!1,this._tiles)this._removeTile(t);this._cache.reset();},i.prototype.tilesIn=function(e,i,o){var r=this,a=[],n=this.transform;if(!n)return a;for(var s=o?n.getCameraQueryGeometry(e):e,l=e.map((function(t){return n.pointCoordinate(t)})),c=s.map((function(t){return n.pointCoordinate(t)})),u=this.getIds(),h=1/0,p=1/0,d=-1/0,_=-1/0,f=0,m=c;f=0&&g[1].y+m>=0){var v=l.map((function(t){return s.getTilePoint(t)})),y=c.map((function(t){return s.getTilePoint(t)}));a.push({tile:o,tileID:s,queryGeometry:v,cameraQueryGeometry:y,scale:f});}}},y=0;y=t.browser.now())return !0}return !1},i.prototype.setFeatureState=function(t,e,i){this._state.updateState(t=t||"_geojsonTileLayer",e,i);},i.prototype.removeFeatureState=function(t,e,i){this._state.removeFeatureState(t=t||"_geojsonTileLayer",e,i);},i.prototype.getFeatureState=function(t,e){return this._state.getState(t=t||"_geojsonTileLayer",e)},i.prototype.setDependencies=function(t,e,i){var o=this._tiles[t];o&&o.setDependencies(e,i);},i.prototype.reloadTilesForDependencies=function(t,e){for(var i in this._tiles)this._tiles[i].hasDependency(t,e)&&this._reloadTile(i,"reloading");this._cache.filter((function(i){return !i.hasDependency(t,e)}));},i}(t.Evented);function Mt(t,e){var i=Math.abs(2*t.wrap)-+(t.wrap<0),o=Math.abs(2*e.wrap)-+(e.wrap<0);return t.overscaledZ-e.overscaledZ||o-i||e.canonical.y-t.canonical.y||e.canonical.x-t.canonical.x}function Lt(t){return "raster"===t||"image"===t||"video"===t}function At(){return new t.window.Worker(Wr.workerUrl)}Dt.maxOverzooming=10,Dt.maxUnderzooming=3;var Rt="mapboxgl_preloaded_worker_pool",kt=function(){this.active={};};kt.prototype.acquire=function(t){if(!this.workers)for(this.workers=[];this.workers.length0?(r-n)/s:0;return this.points[a].mult(1-l).add(this.points[i].mult(l))};var Yt=function(t,e,i){var o=this.boxCells=[],r=this.circleCells=[];this.xCellCount=Math.ceil(t/i),this.yCellCount=Math.ceil(e/i);for(var a=0;a=-e[0]&&i<=e[0]&&o>=-e[1]&&o<=e[1]}function ie(e,i,o,r,a,n,s,l){var c=r?e.textSizeData:e.iconSizeData,u=t.evaluateSizeForZoom(c,o.transform.zoom),h=[256/o.width*2+1,256/o.height*2+1],p=r?e.text.dynamicLayoutVertexArray:e.icon.dynamicLayoutVertexArray;p.clear();for(var d=e.lineVertexArray,_=r?e.text.placedSymbolArray:e.icon.placedSymbolArray,f=o.transform.width/o.transform.height,m=!1,g=0;g<_.length;g++){var v=_.get(g);if(v.hidden||v.writingMode===t.WritingMode.vertical&&!m)ce(v.numGlyphs,p);else {m=!1;var y=[v.anchorX,v.anchorY,0,1];if(t.transformMat4(y,y,i),ee(y,h)){var x=te(o.transform.cameraToCenterDistance,y[3]),b=t.evaluateSizeForFeature(c,u,v),w=s?b/x:b*x,T=new t.Point(v.anchorX,v.anchorY),E=$t(T,a).point,I={},P=ae(v,w,!1,l,i,a,n,e.glyphOffsetArray,d,p,E,T,I,f);m=P.useVertical,(P.notEnoughRoom||m||P.needsFlipping&&ae(v,w,!0,l,i,a,n,e.glyphOffsetArray,d,p,E,T,I,f).notEnoughRoom)&&ce(v.numGlyphs,p);}else ce(v.numGlyphs,p);}}r?e.text.dynamicLayoutVertexBuffer.updateData(p):e.icon.dynamicLayoutVertexBuffer.updateData(p);}function oe(t,e,i,o,r,a,n,s,l,c,u){var h=s.glyphStartIndex+s.numGlyphs,p=s.lineStartIndex,d=s.lineStartIndex+s.lineLength,_=e.getoffsetX(s.glyphStartIndex),f=e.getoffsetX(h-1),m=se(t*_,i,o,r,a,n,s.segment,p,d,l,c,u);if(!m)return null;var g=se(t*f,i,o,r,a,n,s.segment,p,d,l,c,u);return g?{first:m,last:g}:null}function re(e,i,o,r){return e===t.WritingMode.horizontal&&Math.abs(o.y-i.y)>Math.abs(o.x-i.x)*r?{useVertical:!0}:(e===t.WritingMode.vertical?i.yo.x)?{needsFlipping:!0}:null}function ae(e,i,o,r,a,n,s,l,c,u,h,p,d,_){var f,m=i/24,g=e.lineOffsetX*m,v=e.lineOffsetY*m;if(e.numGlyphs>1){var y=e.glyphStartIndex+e.numGlyphs,x=e.lineStartIndex,b=e.lineStartIndex+e.lineLength,w=oe(m,l,g,v,o,h,p,e,c,n,d);if(!w)return {notEnoughRoom:!0};var T=$t(w.first.point,s).point,E=$t(w.last.point,s).point;if(r&&!o){var I=re(e.writingMode,T,E,_);if(I)return I}f=[w.first];for(var P=e.glyphStartIndex+1;P0?D.point:ne(p,z,S,1,a),L=re(e.writingMode,S,M,_);if(L)return L}var A=se(m*l.getoffsetX(e.glyphStartIndex),g,v,o,h,p,e.segment,e.lineStartIndex,e.lineStartIndex+e.lineLength,c,n,d);if(!A)return {notEnoughRoom:!0};f=[A];}for(var R=0,k=f;R0?1:-1,f=0;r&&(_*=-1,f=Math.PI),_<0&&(f+=Math.PI);for(var m=_>0?l+s:l+s+1,g=a,v=a,y=0,x=0,b=Math.abs(d),w=[];y+x<=b;){if((m+=_)=c)return null;if(v=g,w.push(g),void 0===(g=p[m])){var T=new t.Point(u.getx(m),u.gety(m)),E=$t(T,h);if(E.signedDistanceFromCamera>0)g=p[m]=E.point;else {var I=m-_;g=ne(0===y?n:new t.Point(u.getx(I),u.gety(I)),T,v,b-y+1,h);}}y+=x,x=v.dist(g);}var P=(b-y)/x,S=g.sub(v),C=S.mult(P)._add(v);C._add(S._unit()._perp()._mult(o*_));var z=f+Math.atan2(g.y-v.y,g.x-v.x);return w.push(C),{point:C,angle:z,path:w}}Yt.prototype.keysLength=function(){return this.boxKeys.length+this.circleKeys.length},Yt.prototype.insert=function(t,e,i,o,r){this._forEachCell(e,i,o,r,this._insertBoxCell,this.boxUid++),this.boxKeys.push(t),this.bboxes.push(e),this.bboxes.push(i),this.bboxes.push(o),this.bboxes.push(r);},Yt.prototype.insertCircle=function(t,e,i,o){this._forEachCell(e-o,i-o,e+o,i+o,this._insertCircleCell,this.circleUid++),this.circleKeys.push(t),this.circles.push(e),this.circles.push(i),this.circles.push(o);},Yt.prototype._insertBoxCell=function(t,e,i,o,r,a){this.boxCells[r].push(a);},Yt.prototype._insertCircleCell=function(t,e,i,o,r,a){this.circleCells[r].push(a);},Yt.prototype._query=function(t,e,i,o,r,a){if(i<0||t>this.width||o<0||e>this.height)return !r&&[];var n=[];if(t<=0&&e<=0&&this.width<=i&&this.height<=o){if(r)return !0;for(var s=0;s0:n},Yt.prototype._queryCircle=function(t,e,i,o,r){var a=t-i,n=t+i,s=e-i,l=e+i;if(n<0||a>this.width||l<0||s>this.height)return !o&&[];var c=[];return this._forEachCell(a,s,n,l,this._queryCellCircle,c,{hitTest:o,circle:{x:t,y:e,radius:i},seenUids:{box:{},circle:{}}},r),o?c.length>0:c},Yt.prototype.query=function(t,e,i,o,r){return this._query(t,e,i,o,!1,r)},Yt.prototype.hitTest=function(t,e,i,o,r){return this._query(t,e,i,o,!0,r)},Yt.prototype.hitTestCircle=function(t,e,i,o){return this._queryCircle(t,e,i,!0,o)},Yt.prototype._queryCell=function(t,e,i,o,r,a,n,s){var l=n.seenUids,c=this.boxCells[r];if(null!==c)for(var u=this.bboxes,h=0,p=c;h=u[_+0]&&o>=u[_+1]&&(!s||s(this.boxKeys[d]))){if(n.hitTest)return a.push(!0),!0;a.push({key:this.boxKeys[d],x1:u[_],y1:u[_+1],x2:u[_+2],y2:u[_+3]});}}}var f=this.circleCells[r];if(null!==f)for(var m=this.circles,g=0,v=f;gn*n+s*s},Yt.prototype._circleAndRectCollide=function(t,e,i,o,r,a,n){var s=(a-o)/2,l=Math.abs(t-(o+s));if(l>s+i)return !1;var c=(n-r)/2,u=Math.abs(e-(r+c));if(u>c+i)return !1;if(l<=s||u<=c)return !0;var h=l-s,p=u-c;return h*h+p*p<=i*i};var le=new Float32Array([-1/0,-1/0,0,-1/0,-1/0,0,-1/0,-1/0,0,-1/0,-1/0,0]);function ce(t,e){for(var i=0;i=1;M--)D.push(C.path[M]);for(var L=1;L0){for(var B=D[0].clone(),O=D[0].clone(),F=1;F=I.x&&O.x<=P.x&&B.y>=I.y&&O.y<=P.y?[D]:O.xP.x||O.yP.y?[]:t.clipLine([D],I.x,I.y,P.x,P.y);}for(var U=0,N=k;U=this.screenRightBoundary||o<100||e>this.screenBottomBoundary},he.prototype.isInsideGrid=function(t,e,i,o){return i>=0&&t=0&&e0?(this.prevPlacement&&this.prevPlacement.variableOffsets[h.crossTileID]&&this.prevPlacement.placements[h.crossTileID]&&this.prevPlacement.placements[h.crossTileID].text&&(f=this.prevPlacement.variableOffsets[h.crossTileID].anchor),this.variableOffsets[h.crossTileID]={textOffset:m,width:i,height:o,anchor:t,textBoxScale:r,prevAnchor:f},this.markUsedJustification(p,t,h,d),p.allowVerticalPlacement&&(this.markUsedOrientation(p,d,h),this.placedOrientations[h.crossTileID]=d),{shift:g,placedGlyphBoxes:v}):void 0},be.prototype.placeLayerBucketPart=function(e,i,o){var r=this,a=e.parameters,n=a.bucket,s=a.layout,l=a.posMatrix,c=a.textLabelPlaneMatrix,u=a.labelToScreenMatrix,h=a.textPixelRatio,p=a.holdingForFade,d=a.collisionBoxArray,_=a.partiallyEvaluatedTextSize,f=a.collisionGroup,m=s.get("text-optional"),g=s.get("icon-optional"),v=s.get("text-allow-overlap"),y=s.get("icon-allow-overlap"),x="map"===s.get("text-rotation-alignment"),b="map"===s.get("text-pitch-alignment"),w="none"!==s.get("icon-text-fit"),T="viewport-y"===s.get("symbol-z-order"),E=v&&(y||!n.hasIconData()||g),I=y&&(v||!n.hasTextData()||m);!n.collisionArrays&&d&&n.deserializeCollisionBoxes(d);var P=function(e,a){if(!i[e.crossTileID])if(p)r.placements[e.crossTileID]=new fe(!1,!1,!1);else {var d,T=!1,P=!1,S=!0,C=null,z={box:null,offscreen:null},D={box:null,offscreen:null},M=null,L=null,A=0,R=0,k=0;a.textFeatureIndex?A=a.textFeatureIndex:e.useRuntimeCollisionCircles&&(A=e.featureIndex),a.verticalTextFeatureIndex&&(R=a.verticalTextFeatureIndex);var B=a.textBox;if(B){var O=function(i){var o=t.WritingMode.horizontal;if(n.allowVerticalPlacement&&!i&&r.prevPlacement){var a=r.prevPlacement.placedOrientations[e.crossTileID];a&&(r.placedOrientations[e.crossTileID]=a,r.markUsedOrientation(n,o=a,e));}return o},F=function(i,o){if(n.allowVerticalPlacement&&e.numVerticalGlyphVertices>0&&a.verticalTextBox)for(var r=0,s=n.writingModes;r0&&(U=U.filter((function(t){return t!==N.anchor}))).unshift(N.anchor);}var Z=function(t,i,o){for(var a=t.x2-t.x1,s=t.y2-t.y1,c=e.textBoxScale,u=w&&!y?i:null,p={box:[],offscreen:!1},d=v?2*U.length:U.length,_=0;_=U.length,e,n,o,u);if(m&&(p=m.placedGlyphBoxes)&&p.box&&p.box.length){T=!0,C=m.shift;break}}return p};F((function(){return Z(B,a.iconBox,t.WritingMode.horizontal)}),(function(){var i=a.verticalTextBox;return n.allowVerticalPlacement&&!(z&&z.box&&z.box.length)&&e.numVerticalGlyphVertices>0&&i?Z(i,a.verticalIconBox,t.WritingMode.vertical):{box:null,offscreen:null}})),z&&(T=z.box,S=z.offscreen);var j=O(z&&z.box);if(!T&&r.prevPlacement){var q=r.prevPlacement.variableOffsets[e.crossTileID];q&&(r.variableOffsets[e.crossTileID]=q,r.markUsedJustification(n,q.anchor,e,j));}}else {var V=function(t,i){var o=r.collisionIndex.placeCollisionBox(t,v,h,l,f.predicate);return o&&o.box&&o.box.length&&(r.markUsedOrientation(n,i,e),r.placedOrientations[e.crossTileID]=i),o};F((function(){return V(B,t.WritingMode.horizontal)}),(function(){var i=a.verticalTextBox;return n.allowVerticalPlacement&&e.numVerticalGlyphVertices>0&&i?V(i,t.WritingMode.vertical):{box:null,offscreen:null}})),O(z&&z.box&&z.box.length);}}if(T=(d=z)&&d.box&&d.box.length>0,S=d&&d.offscreen,e.useRuntimeCollisionCircles){var G=n.text.placedSymbolArray.get(e.centerJustifiedTextSymbolIndex),W=t.evaluateSizeForFeature(n.textSizeData,_,G),X=s.get("text-padding");M=r.collisionIndex.placeCollisionCircles(v,G,n.lineVertexArray,n.glyphOffsetArray,W,l,c,u,o,b,f.predicate,e.collisionCircleDiameter,X),T=v||M.circles.length>0&&!M.collisionDetected,S=S&&M.offscreen;}if(a.iconFeatureIndex&&(k=a.iconFeatureIndex),a.iconBox){var H=function(t){var e=w&&C?xe(t,C.x,C.y,x,b,r.transform.angle):t;return r.collisionIndex.placeCollisionBox(e,y,h,l,f.predicate)};P=D&&D.box&&D.box.length&&a.verticalIconBox?(L=H(a.verticalIconBox)).box.length>0:(L=H(a.iconBox)).box.length>0,S=S&&L.offscreen;}var K=m||0===e.numHorizontalGlyphVertices&&0===e.numVerticalGlyphVertices,Y=g||0===e.numIconVertices;if(K||Y?Y?K||(P=P&&T):T=P&&T:P=T=P&&T,T&&d&&d.box&&r.collisionIndex.insertCollisionBox(d.box,s.get("text-ignore-placement"),n.bucketInstanceId,D&&D.box&&R?R:A,f.ID),P&&L&&r.collisionIndex.insertCollisionBox(L.box,s.get("icon-ignore-placement"),n.bucketInstanceId,k,f.ID),M&&(T&&r.collisionIndex.insertCollisionCircles(M.circles,s.get("text-ignore-placement"),n.bucketInstanceId,A,f.ID),o)){var J=n.bucketInstanceId,Q=r.collisionCircleArrays[J];void 0===Q&&(Q=r.collisionCircleArrays[J]=new me);for(var $=0;$=0;--C){var z=S[C];P(n.symbolInstances.get(z),n.collisionArrays[z]);}else for(var D=e.symbolInstanceStart;D=0&&(e.text.placedSymbolArray.get(l).crossTileID=a>=0&&l!==a?0:o.crossTileID);}},be.prototype.markUsedOrientation=function(e,i,o){for(var r=i===t.WritingMode.horizontal||i===t.WritingMode.horizontalOnly?i:0,a=i===t.WritingMode.vertical?i:0,n=0,s=[o.leftJustifiedTextSymbolIndex,o.centerJustifiedTextSymbolIndex,o.rightJustifiedTextSymbolIndex];n0,v=r.placedOrientations[a.crossTileID],y=v===t.WritingMode.vertical,x=v===t.WritingMode.horizontal||v===t.WritingMode.horizontalOnly;if(s>0||l>0){var b=De(m.text);_(e.text,s,y?Me:b),_(e.text,l,x?Me:b);var w=m.text.isHidden();[a.rightJustifiedTextSymbolIndex,a.centerJustifiedTextSymbolIndex,a.leftJustifiedTextSymbolIndex].forEach((function(t){t>=0&&(e.text.placedSymbolArray.get(t).hidden=w||y?1:0);})),a.verticalPlacedTextSymbolIndex>=0&&(e.text.placedSymbolArray.get(a.verticalPlacedTextSymbolIndex).hidden=w||x?1:0);var T=r.variableOffsets[a.crossTileID];T&&r.markUsedJustification(e,T.anchor,a,v);var E=r.placedOrientations[a.crossTileID];E&&(r.markUsedJustification(e,"left",a,E),r.markUsedOrientation(e,E,a));}if(g){var I=De(m.icon),P=!(p&&a.verticalPlacedIconSymbolIndex&&y);a.placedIconSymbolIndex>=0&&(_(e.icon,a.numIconVertices,P?I:Me),e.icon.placedSymbolArray.get(a.placedIconSymbolIndex).hidden=m.icon.isHidden()),a.verticalPlacedIconSymbolIndex>=0&&(_(e.icon,a.numVerticalIconVertices,P?Me:I),e.icon.placedSymbolArray.get(a.verticalPlacedIconSymbolIndex).hidden=m.icon.isHidden());}if(e.hasIconCollisionBoxData()||e.hasTextCollisionBoxData()){var S=e.collisionArrays[o];if(S){var C=new t.Point(0,0);if(S.textBox||S.verticalTextBox){var z=!0;if(c){var D=r.variableOffsets[f];D?(C=ye(D.anchor,D.width,D.height,D.textOffset,D.textBoxScale),u&&C._rotate(h?r.transform.angle:-r.transform.angle)):z=!1;}S.textBox&&we(e.textCollisionBox.collisionVertexArray,m.text.placed,!z||y,C.x,C.y),S.verticalTextBox&&we(e.textCollisionBox.collisionVertexArray,m.text.placed,!z||x,C.x,C.y);}var M=Boolean(!x&&S.verticalIconBox);S.iconBox&&we(e.iconCollisionBox.collisionVertexArray,m.icon.placed,M,p?C.x:0,p?C.y:0),S.verticalIconBox&&we(e.iconCollisionBox.collisionVertexArray,m.icon.placed,!M,p?C.x:0,p?C.y:0);}}},m=0;mt},be.prototype.setStale=function(){this.stale=!0;};var Te=Math.pow(2,25),Ee=Math.pow(2,24),Ie=Math.pow(2,17),Pe=Math.pow(2,16),Se=Math.pow(2,9),Ce=Math.pow(2,8),ze=Math.pow(2,1);function De(t){if(0===t.opacity&&!t.placed)return 0;if(1===t.opacity&&t.placed)return 4294967295;var e=t.placed?1:0,i=Math.floor(127*t.opacity);return i*Te+e*Ee+i*Ie+e*Pe+i*Se+e*Ce+i*ze+e}var Me=0,Le=function(t){this._sortAcrossTiles="viewport-y"!==t.layout.get("symbol-z-order")&&void 0!==t.layout.get("symbol-sort-key").constantOr(1),this._currentTileIndex=0,this._currentPartIndex=0,this._seenCrossTileIDs={},this._bucketParts=[];};Le.prototype.continuePlacement=function(t,e,i,o,r){for(var a=this._bucketParts;this._currentTileIndex2};this._currentPlacementIndex>=0;){var s=i[e[this._currentPlacementIndex]],l=this.placement.collisionIndex.transform.zoom;if("symbol"===s.type&&(!s.minzoom||s.minzoom<=l)&&(!s.maxzoom||s.maxzoom>l)){if(this._inProgressLayer||(this._inProgressLayer=new Le(s)),this._inProgressLayer.continuePlacement(o[s.source],this.placement,this._showCollisionBoxes,s,n))return;delete this._inProgressLayer;}this._currentPlacementIndex--;}this._done=!0;},Ae.prototype.commit=function(t){return this.placement.commit(t),this.placement};var Re=512/t.EXTENT/2,ke=function(t,e,i){this.tileID=t,this.indexedSymbolInstances={},this.bucketInstanceId=i;for(var o=0;ot.overscaledZ)for(var s in n){var l=n[s];l.tileID.isChildOf(t)&&l.findMatches(e.symbolInstances,t,r);}else {var c=n[t.scaledTo(Number(a)).key];c&&c.findMatches(e.symbolInstances,t,r);}}for(var u=0;u1?"@2x":"",l=t.getJSON(i.transformRequest(i.normalizeSpriteURL(e,s,".json"),t.ResourceType.SpriteJSON),(function(t,e){l=null,n||(n=t,r=e,u());})),c=t.getImage(i.transformRequest(i.normalizeSpriteURL(e,s,".png"),t.ResourceType.SpriteImage),(function(t,e){c=null,n||(n=t,a=e,u());}));function u(){if(n)o(n);else if(r&&a){var e=t.browser.getImageData(a),i={};for(var s in r){var l=r[s],c=l.width,u=l.height,h=l.x,p=l.y,d=l.sdf,_=l.pixelRatio,f=l.stretchX,m=l.stretchY,g=l.content,v=new t.RGBAImage({width:c,height:u});t.RGBAImage.copy(e,v,{x:h,y:p},{x:0,y:0},{width:c,height:u}),i[s]={data:v,pixelRatio:_,sdf:d,stretchX:f,stretchY:m,content:g};}o(null,i);}}return {cancel:function(){l&&(l.cancel(),l=null),c&&(c.cancel(),c=null);}}}(e,this.map._requestManager,(function(e,o){if(i._spriteRequest=null,e)i.fire(new t.ErrorEvent(e));else if(o)for(var r in o)i.imageManager.addImage(r,o[r]);i.imageManager.setLoaded(!0),i._availableImages=i.imageManager.listImages(),i.dispatcher.broadcast("setImages",i._availableImages),i.fire(new t.Event("data",{dataType:"style"}));}));},i.prototype._validateLayer=function(e){var i=this.sourceCaches[e.source];if(i){var o=e.sourceLayer;if(o){var r=i.getSource();("geojson"===r.type||r.vectorLayerIds&&-1===r.vectorLayerIds.indexOf(o))&&this.fire(new t.ErrorEvent(new Error('Source layer "'+o+'" does not exist on source "'+r.id+'" as specified by style layer "'+e.id+'"')));}}},i.prototype.loaded=function(){if(!this._loaded)return !1;if(Object.keys(this._updatedSources).length)return !1;for(var t in this.sourceCaches)if(!this.sourceCaches[t].loaded())return !1;return !!this.imageManager.isLoaded()},i.prototype._serializeLayers=function(t){for(var e=[],i=0,o=t;i0)throw new Error("Unimplemented: "+r.map((function(t){return t.command})).join(", ")+".");return o.forEach((function(t){"setTransition"!==t.command&&i[t.command].apply(i,t.args);})),this.stylesheet=e,!0},i.prototype.addImage=function(e,i){if(this.getImage(e))return this.fire(new t.ErrorEvent(new Error("An image with this name already exists.")));this.imageManager.addImage(e,i),this._availableImages=this.imageManager.listImages(),this._changedImages[e]=!0,this._changed=!0,this.fire(new t.Event("data",{dataType:"style"}));},i.prototype.updateImage=function(t,e){this.imageManager.updateImage(t,e);},i.prototype.getImage=function(t){return this.imageManager.getImage(t)},i.prototype.removeImage=function(e){if(!this.getImage(e))return this.fire(new t.ErrorEvent(new Error("No image with this name exists.")));this.imageManager.removeImage(e),this._availableImages=this.imageManager.listImages(),this._changedImages[e]=!0,this._changed=!0,this.fire(new t.Event("data",{dataType:"style"}));},i.prototype.listImages=function(){return this._checkLoaded(),this.imageManager.listImages()},i.prototype.addSource=function(e,i,o){var r=this;if(void 0===o&&(o={}),this._checkLoaded(),void 0!==this.sourceCaches[e])throw new Error("There is already a source with this ID");if(!i.type)throw new Error("The type property must be defined, but the only the following properties were given: "+Object.keys(i).join(", ")+".");if(!(["vector","raster","geojson","video","image"].indexOf(i.type)>=0&&this._validate(t.validateStyle.source,"sources."+e,i,null,o))){this.map&&this.map._collectResourceTiming&&(i.collectResourceTiming=!0);var a=this.sourceCaches[e]=new Dt(e,i,this.dispatcher);a.style=this,a.setEventedParent(this,(function(){return {isSourceLoaded:r.loaded(),source:a.serialize(),sourceId:e}})),a.onAdd(this.map),this._changed=!0;}},i.prototype.removeSource=function(e){if(this._checkLoaded(),void 0===this.sourceCaches[e])throw new Error("There is no source with this ID");for(var i in this._layers)if(this._layers[i].source===e)return this.fire(new t.ErrorEvent(new Error('Source "'+e+'" cannot be removed while layer "'+i+'" is using it.')));var o=this.sourceCaches[e];delete this.sourceCaches[e],delete this._updatedSources[e],o.fire(new t.Event("data",{sourceDataType:"metadata",dataType:"source",sourceId:e})),o.setEventedParent(null),o.clearTiles(),o.onRemove&&o.onRemove(this.map),this._changed=!0;},i.prototype.setGeoJSONSourceData=function(t,e){this._checkLoaded(),this.sourceCaches[t].getSource().setData(e),this._changed=!0;},i.prototype.getSource=function(t){return this.sourceCaches[t]&&this.sourceCaches[t].getSource()},i.prototype.addLayer=function(e,i,o){void 0===o&&(o={}),this._checkLoaded();var r=e.id;if(this.getLayer(r))this.fire(new t.ErrorEvent(new Error('Layer with id "'+r+'" already exists on this map')));else {var a;if("custom"===e.type){if(Ue(this,t.validateCustomStyleLayer(e)))return;a=t.createStyleLayer(e);}else {if("object"==typeof e.source&&(this.addSource(r,e.source),e=t.clone$1(e),e=t.extend(e,{source:r})),this._validate(t.validateStyle.layer,"layers."+r,e,{arrayIndex:-1},o))return;a=t.createStyleLayer(e),this._validateLayer(a),a.setEventedParent(this,{layer:{id:r}}),this._serializedLayers[a.id]=a.serialize();}var n=i?this._order.indexOf(i):this._order.length;if(i&&-1===n)this.fire(new t.ErrorEvent(new Error('Layer with id "'+i+'" does not exist on this map.')));else {if(this._order.splice(n,0,r),this._layerOrderChanged=!0,this._layers[r]=a,this._removedLayers[r]&&a.source&&"custom"!==a.type){var s=this._removedLayers[r];delete this._removedLayers[r],s.type!==a.type?this._updatedSources[a.source]="clear":(this._updatedSources[a.source]="reload",this.sourceCaches[a.source].pause());}this._updateLayer(a),a.onAdd&&a.onAdd(this.map);}}},i.prototype.moveLayer=function(e,i){if(this._checkLoaded(),this._changed=!0,this._layers[e]){if(e!==i){var o=this._order.indexOf(e);this._order.splice(o,1);var r=i?this._order.indexOf(i):this._order.length;i&&-1===r?this.fire(new t.ErrorEvent(new Error('Layer with id "'+i+'" does not exist on this map.'))):(this._order.splice(r,0,e),this._layerOrderChanged=!0);}}else this.fire(new t.ErrorEvent(new Error("The layer '"+e+"' does not exist in the map's style and cannot be moved.")));},i.prototype.removeLayer=function(e){this._checkLoaded();var i=this._layers[e];if(i){i.setEventedParent(null);var o=this._order.indexOf(e);this._order.splice(o,1),this._layerOrderChanged=!0,this._changed=!0,this._removedLayers[e]=i,delete this._layers[e],delete this._serializedLayers[e],delete this._updatedLayers[e],delete this._updatedPaintProps[e],i.onRemove&&i.onRemove(this.map);}else this.fire(new t.ErrorEvent(new Error("The layer '"+e+"' does not exist in the map's style and cannot be removed.")));},i.prototype.getLayer=function(t){return this._layers[t]},i.prototype.hasLayer=function(t){return t in this._layers},i.prototype.setLayerZoomRange=function(e,i,o){this._checkLoaded();var r=this.getLayer(e);r?r.minzoom===i&&r.maxzoom===o||(null!=i&&(r.minzoom=i),null!=o&&(r.maxzoom=o),this._updateLayer(r)):this.fire(new t.ErrorEvent(new Error("The layer '"+e+"' does not exist in the map's style and cannot have zoom extent.")));},i.prototype.setFilter=function(e,i,o){void 0===o&&(o={}),this._checkLoaded();var r=this.getLayer(e);if(r){if(!t.deepEqual(r.filter,i))return null==i?(r.filter=void 0,void this._updateLayer(r)):void(this._validate(t.validateStyle.filter,"layers."+r.id+".filter",i,null,o)||(r.filter=t.clone$1(i),this._updateLayer(r)))}else this.fire(new t.ErrorEvent(new Error("The layer '"+e+"' does not exist in the map's style and cannot be filtered.")));},i.prototype.getFilter=function(e){return t.clone$1(this.getLayer(e).filter)},i.prototype.setLayoutProperty=function(e,i,o,r){void 0===r&&(r={}),this._checkLoaded();var a=this.getLayer(e);a?t.deepEqual(a.getLayoutProperty(i),o)||(a.setLayoutProperty(i,o,r),this._updateLayer(a)):this.fire(new t.ErrorEvent(new Error("The layer '"+e+"' does not exist in the map's style and cannot be styled.")));},i.prototype.getLayoutProperty=function(e,i){var o=this.getLayer(e);if(o)return o.getLayoutProperty(i);this.fire(new t.ErrorEvent(new Error("The layer '"+e+"' does not exist in the map's style.")));},i.prototype.setPaintProperty=function(e,i,o,r){void 0===r&&(r={}),this._checkLoaded();var a=this.getLayer(e);a?t.deepEqual(a.getPaintProperty(i),o)||(a.setPaintProperty(i,o,r)&&this._updateLayer(a),this._changed=!0,this._updatedPaintProps[e]=!0):this.fire(new t.ErrorEvent(new Error("The layer '"+e+"' does not exist in the map's style and cannot be styled.")));},i.prototype.getPaintProperty=function(t,e){return this.getLayer(t).getPaintProperty(e)},i.prototype.setFeatureState=function(e,i){this._checkLoaded();var o=e.source,r=e.sourceLayer,a=this.sourceCaches[o];if(void 0!==a){var n=a.getSource().type;"geojson"===n&&r?this.fire(new t.ErrorEvent(new Error("GeoJSON sources cannot have a sourceLayer parameter."))):"vector"!==n||r?(void 0===e.id&&this.fire(new t.ErrorEvent(new Error("The feature id parameter must be provided."))),a.setFeatureState(r,e.id,i)):this.fire(new t.ErrorEvent(new Error("The sourceLayer parameter must be provided for vector source types.")));}else this.fire(new t.ErrorEvent(new Error("The source '"+o+"' does not exist in the map's style.")));},i.prototype.removeFeatureState=function(e,i){this._checkLoaded();var o=e.source,r=this.sourceCaches[o];if(void 0!==r){var a=r.getSource().type,n="vector"===a?e.sourceLayer:void 0;"vector"!==a||n?i&&"string"!=typeof e.id&&"number"!=typeof e.id?this.fire(new t.ErrorEvent(new Error("A feature id is requred to remove its specific state property."))):r.removeFeatureState(n,e.id,i):this.fire(new t.ErrorEvent(new Error("The sourceLayer parameter must be provided for vector source types.")));}else this.fire(new t.ErrorEvent(new Error("The source '"+o+"' does not exist in the map's style.")));},i.prototype.getFeatureState=function(e){this._checkLoaded();var i=e.source,o=e.sourceLayer,r=this.sourceCaches[i];if(void 0!==r){if("vector"!==r.getSource().type||o)return void 0===e.id&&this.fire(new t.ErrorEvent(new Error("The feature id parameter must be provided."))),r.getFeatureState(o,e.id);this.fire(new t.ErrorEvent(new Error("The sourceLayer parameter must be provided for vector source types.")));}else this.fire(new t.ErrorEvent(new Error("The source '"+i+"' does not exist in the map's style.")));},i.prototype.getTransition=function(){return t.extend({duration:300,delay:0},this.stylesheet&&this.stylesheet.transition)},i.prototype.serialize=function(){return t.filterObject({version:this.stylesheet.version,name:this.stylesheet.name,metadata:this.stylesheet.metadata,light:this.stylesheet.light,center:this.stylesheet.center,zoom:this.stylesheet.zoom,bearing:this.stylesheet.bearing,pitch:this.stylesheet.pitch,sprite:this.stylesheet.sprite,glyphs:this.stylesheet.glyphs,transition:this.stylesheet.transition,sources:t.mapObject(this.sourceCaches,(function(t){return t.serialize()})),layers:this._serializeLayers(this._order)},(function(t){return void 0!==t}))},i.prototype._updateLayer=function(t){this._updatedLayers[t.id]=!0,t.source&&!this._updatedSources[t.source]&&"raster"!==this.sourceCaches[t.source].getSource().type&&(this._updatedSources[t.source]="reload",this.sourceCaches[t.source].pause()),this._changed=!0;},i.prototype._flattenAndSortRenderedFeatures=function(t){for(var e=this,i=function(t){return "fill-extrusion"===e._layers[t].type},o={},r=[],a=this._order.length-1;a>=0;a--){var n=this._order[a];if(i(n)){o[n]=a;for(var s=0,l=t;s=0;d--){var _=this._order[d];if(i(_))for(var f=r.length-1;f>=0;f--){var m=r[f].feature;if(o[m.layer.id] 0.5) {gl_FragColor=vec4(0.0,0.0,1.0,0.5)*alpha;}if (v_notUsed > 0.5) {gl_FragColor*=.1;}}","attribute vec2 a_pos;attribute vec2 a_anchor_pos;attribute vec2 a_extrude;attribute vec2 a_placed;attribute vec2 a_shift;uniform mat4 u_matrix;uniform vec2 u_extrude_scale;uniform float u_camera_to_center_distance;varying float v_placed;varying float v_notUsed;void main() {vec4 projectedPoint=u_matrix*vec4(a_anchor_pos,0,1);highp float camera_to_anchor_distance=projectedPoint.w;highp float collision_perspective_ratio=clamp(0.5+0.5*(u_camera_to_center_distance/camera_to_anchor_distance),0.0,4.0);gl_Position=u_matrix*vec4(a_pos,0.0,1.0);gl_Position.xy+=(a_extrude+a_shift)*u_extrude_scale*gl_Position.w*collision_perspective_ratio;v_placed=a_placed.x;v_notUsed=a_placed.y;}"),$e=gi("varying float v_radius;varying vec2 v_extrude;varying float v_perspective_ratio;varying float v_collision;void main() {float alpha=0.5*min(v_perspective_ratio,1.0);float stroke_radius=0.9*max(v_perspective_ratio,1.0);float distance_to_center=length(v_extrude);float distance_to_edge=abs(distance_to_center-v_radius);float opacity_t=smoothstep(-stroke_radius,0.0,-distance_to_edge);vec4 color=mix(vec4(0.0,0.0,1.0,0.5),vec4(1.0,0.0,0.0,1.0),v_collision);gl_FragColor=color*alpha*opacity_t;}","attribute vec2 a_pos;attribute float a_radius;attribute vec2 a_flags;uniform mat4 u_matrix;uniform mat4 u_inv_matrix;uniform vec2 u_viewport_size;uniform float u_camera_to_center_distance;varying float v_radius;varying vec2 v_extrude;varying float v_perspective_ratio;varying float v_collision;vec3 toTilePosition(vec2 screenPos) {vec4 rayStart=u_inv_matrix*vec4(screenPos,-1.0,1.0);vec4 rayEnd =u_inv_matrix*vec4(screenPos, 1.0,1.0);rayStart.xyz/=rayStart.w;rayEnd.xyz /=rayEnd.w;highp float t=(0.0-rayStart.z)/(rayEnd.z-rayStart.z);return mix(rayStart.xyz,rayEnd.xyz,t);}void main() {vec2 quadCenterPos=a_pos;float radius=a_radius;float collision=a_flags.x;float vertexIdx=a_flags.y;vec2 quadVertexOffset=vec2(mix(-1.0,1.0,float(vertexIdx >=2.0)),mix(-1.0,1.0,float(vertexIdx >=1.0 && vertexIdx <=2.0)));vec2 quadVertexExtent=quadVertexOffset*radius;vec3 tilePos=toTilePosition(quadCenterPos);vec4 clipPos=u_matrix*vec4(tilePos,1.0);highp float camera_to_anchor_distance=clipPos.w;highp float collision_perspective_ratio=clamp(0.5+0.5*(u_camera_to_center_distance/camera_to_anchor_distance),0.0,4.0);float padding_factor=1.2;v_radius=radius;v_extrude=quadVertexExtent*padding_factor;v_perspective_ratio=collision_perspective_ratio;v_collision=collision;gl_Position=vec4(clipPos.xyz/clipPos.w,1.0)+vec4(quadVertexExtent*padding_factor/u_viewport_size*2.0,0.0,0.0);}"),ti=gi("uniform highp vec4 u_color;uniform sampler2D u_overlay;varying vec2 v_uv;void main() {vec4 overlay_color=texture2D(u_overlay,v_uv);gl_FragColor=mix(u_color,overlay_color,overlay_color.a);}","attribute vec2 a_pos;varying vec2 v_uv;uniform mat4 u_matrix;uniform float u_overlay_scale;void main() {v_uv=a_pos/8192.0;gl_Position=u_matrix*vec4(a_pos*u_overlay_scale,0,1);}"),ei=gi("#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float opacity\ngl_FragColor=color*opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","attribute vec2 a_pos;uniform mat4 u_matrix;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float opacity\ngl_Position=u_matrix*vec4(a_pos,0,1);}"),ii=gi("varying vec2 v_pos;\n#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 outline_color\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_pos-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);gl_FragColor=outline_color*(alpha*opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","attribute vec2 a_pos;uniform mat4 u_matrix;uniform vec2 u_world;varying vec2 v_pos;\n#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 outline_color\n#pragma mapbox: initialize lowp float opacity\ngl_Position=u_matrix*vec4(a_pos,0,1);v_pos=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world;}"),oi=gi("uniform vec2 u_texsize;uniform sampler2D u_image;uniform float u_fade;varying vec2 v_pos_a;varying vec2 v_pos_b;varying vec2 v_pos;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture2D(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture2D(u_image,pos2);float dist=length(v_pos-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);gl_FragColor=mix(color1,color2,u_fade)*alpha*opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec2 u_world;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec3 u_scale;attribute vec2 a_pos;varying vec2 v_pos_a;varying vec2 v_pos_b;varying vec2 v_pos;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;gl_Position=u_matrix*vec4(a_pos,0,1);vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileRatio,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileRatio,a_pos);v_pos=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world;}"),ri=gi("uniform vec2 u_texsize;uniform float u_fade;uniform sampler2D u_image;varying vec2 v_pos_a;varying vec2 v_pos_b;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture2D(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture2D(u_image,pos2);gl_FragColor=mix(color1,color2,u_fade)*opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec3 u_scale;attribute vec2 a_pos;varying vec2 v_pos_a;varying vec2 v_pos_b;\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileZoomRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;gl_Position=u_matrix*vec4(a_pos,0,1);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileZoomRatio,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileZoomRatio,a_pos);}"),ai=gi("varying vec4 v_color;void main() {gl_FragColor=v_color;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp float u_lightintensity;uniform float u_vertical_gradient;uniform lowp float u_opacity;attribute vec2 a_pos;attribute vec4 a_normal_ed;varying vec4 v_color;\n#pragma mapbox: define highp float base\n#pragma mapbox: define highp float height\n#pragma mapbox: define highp vec4 color\nvoid main() {\n#pragma mapbox: initialize highp float base\n#pragma mapbox: initialize highp float height\n#pragma mapbox: initialize highp vec4 color\nvec3 normal=a_normal_ed.xyz;base=max(0.0,base);height=max(0.0,height);float t=mod(normal.x,2.0);gl_Position=u_matrix*vec4(a_pos,t > 0.0 ? height : base,1);float colorvalue=color.r*0.2126+color.g*0.7152+color.b*0.0722;v_color=vec4(0.0,0.0,0.0,1.0);vec4 ambientlight=vec4(0.03,0.03,0.03,1.0);color+=ambientlight;float directional=clamp(dot(normal/16384.0,u_lightpos),0.0,1.0);directional=mix((1.0-u_lightintensity),max((1.0-colorvalue+u_lightintensity),1.0),directional);if (normal.y !=0.0) {directional*=((1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),mix(0.7,0.98,1.0-u_lightintensity),1.0)));}v_color.r+=clamp(color.r*directional*u_lightcolor.r,mix(0.0,0.3,1.0-u_lightcolor.r),1.0);v_color.g+=clamp(color.g*directional*u_lightcolor.g,mix(0.0,0.3,1.0-u_lightcolor.g),1.0);v_color.b+=clamp(color.b*directional*u_lightcolor.b,mix(0.0,0.3,1.0-u_lightcolor.b),1.0);v_color*=u_opacity;}"),ni=gi("uniform vec2 u_texsize;uniform float u_fade;uniform sampler2D u_image;varying vec2 v_pos_a;varying vec2 v_pos_b;varying vec4 v_lighting;\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float base\n#pragma mapbox: initialize lowp float height\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture2D(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture2D(u_image,pos2);vec4 mixedColor=mix(color1,color2,u_fade);gl_FragColor=mixedColor*v_lighting;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_height_factor;uniform vec3 u_scale;uniform float u_vertical_gradient;uniform lowp float u_opacity;uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp float u_lightintensity;attribute vec2 a_pos;attribute vec4 a_normal_ed;varying vec2 v_pos_a;varying vec2 v_pos_b;varying vec4 v_lighting;\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float base\n#pragma mapbox: initialize lowp float height\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec3 normal=a_normal_ed.xyz;float edgedistance=a_normal_ed.w;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;base=max(0.0,base);height=max(0.0,height);float t=mod(normal.x,2.0);float z=t > 0.0 ? height : base;gl_Position=u_matrix*vec4(a_pos,z,1);vec2 pos=normal.x==1.0 && normal.y==0.0 && normal.z==16384.0\n? a_pos\n: vec2(edgedistance,z*u_height_factor);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileRatio,pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileRatio,pos);v_lighting=vec4(0.0,0.0,0.0,1.0);float directional=clamp(dot(normal/16383.0,u_lightpos),0.0,1.0);directional=mix((1.0-u_lightintensity),max((0.5+u_lightintensity),1.0),directional);if (normal.y !=0.0) {directional*=((1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),mix(0.7,0.98,1.0-u_lightintensity),1.0)));}v_lighting.rgb+=clamp(directional*u_lightcolor,mix(vec3(0.0),vec3(0.3),1.0-u_lightcolor),vec3(1.0));v_lighting*=u_opacity;}"),si=gi("#ifdef GL_ES\nprecision highp float;\n#endif\nuniform sampler2D u_image;varying vec2 v_pos;uniform vec2 u_dimension;uniform float u_zoom;uniform float u_maxzoom;uniform vec4 u_unpack;float getElevation(vec2 coord,float bias) {vec4 data=texture2D(u_image,coord)*255.0;data.a=-1.0;return dot(data,u_unpack)/4.0;}void main() {vec2 epsilon=1.0/u_dimension;float a=getElevation(v_pos+vec2(-epsilon.x,-epsilon.y),0.0);float b=getElevation(v_pos+vec2(0,-epsilon.y),0.0);float c=getElevation(v_pos+vec2(epsilon.x,-epsilon.y),0.0);float d=getElevation(v_pos+vec2(-epsilon.x,0),0.0);float e=getElevation(v_pos,0.0);float f=getElevation(v_pos+vec2(epsilon.x,0),0.0);float g=getElevation(v_pos+vec2(-epsilon.x,epsilon.y),0.0);float h=getElevation(v_pos+vec2(0,epsilon.y),0.0);float i=getElevation(v_pos+vec2(epsilon.x,epsilon.y),0.0);float exaggeration=u_zoom < 2.0 ? 0.4 : u_zoom < 4.5 ? 0.35 : 0.3;vec2 deriv=vec2((c+f+f+i)-(a+d+d+g),(g+h+h+i)-(a+b+b+c))/ pow(2.0,(u_zoom-u_maxzoom)*exaggeration+19.2562-u_zoom);gl_FragColor=clamp(vec4(deriv.x/2.0+0.5,deriv.y/2.0+0.5,1.0,1.0),0.0,1.0);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec2 u_dimension;attribute vec2 a_pos;attribute vec2 a_texture_pos;varying vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);highp vec2 epsilon=1.0/u_dimension;float scale=(u_dimension.x-2.0)/u_dimension.x;v_pos=(a_texture_pos/8192.0)*scale+epsilon;}"),li=gi("uniform sampler2D u_image;varying vec2 v_pos;uniform vec2 u_latrange;uniform vec2 u_light;uniform vec4 u_shadow;uniform vec4 u_highlight;uniform vec4 u_accent;\n#define PI 3.141592653589793\nvoid main() {vec4 pixel=texture2D(u_image,v_pos);vec2 deriv=((pixel.rg*2.0)-1.0);float scaleFactor=cos(radians((u_latrange[0]-u_latrange[1])*(1.0-v_pos.y)+u_latrange[1]));float slope=atan(1.25*length(deriv)/scaleFactor);float aspect=deriv.x !=0.0 ? atan(deriv.y,-deriv.x) : PI/2.0*(deriv.y > 0.0 ? 1.0 :-1.0);float intensity=u_light.x;float azimuth=u_light.y+PI;float base=1.875-intensity*1.75;float maxValue=0.5*PI;float scaledSlope=intensity !=0.5 ? ((pow(base,slope)-1.0)/(pow(base,maxValue)-1.0))*maxValue : slope;float accent=cos(scaledSlope);vec4 accent_color=(1.0-accent)*u_accent*clamp(intensity*2.0,0.0,1.0);float shade=abs(mod((aspect+azimuth)/PI+0.5,2.0)-1.0);vec4 shade_color=mix(u_shadow,u_highlight,shade)*sin(scaledSlope)*clamp(intensity*2.0,0.0,1.0);gl_FragColor=accent_color*(1.0-shade_color.a)+shade_color;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;attribute vec2 a_pos;attribute vec2 a_texture_pos;varying vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);v_pos=a_texture_pos/8192.0;}"),ci=gi("uniform lowp float u_device_pixel_ratio;varying vec2 v_width2;varying vec2 v_normal;varying float v_gamma_scale;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);gl_FragColor=color*(alpha*opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\nattribute vec2 a_pos_normal;attribute vec4 a_data;uniform mat4 u_matrix;uniform mediump float u_ratio;uniform vec2 u_units_to_pixels;uniform lowp float u_device_pixel_ratio;varying vec2 v_normal;varying vec2 v_width2;varying float v_gamma_scale;varying highp float v_linesofar;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;v_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*2.0;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);vec4 projected_extrude=u_matrix*vec4(dist/u_ratio,0.0,0.0);gl_Position=u_matrix*vec4(pos+offset2/u_ratio,0.0,1.0)+projected_extrude;float extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length(projected_extrude.xy/gl_Position.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;v_width2=vec2(outset,inset);}"),ui=gi("uniform lowp float u_device_pixel_ratio;uniform sampler2D u_image;varying vec2 v_width2;varying vec2 v_normal;varying float v_gamma_scale;varying highp float v_lineprogress;\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);vec4 color=texture2D(u_image,vec2(v_lineprogress,0.5));gl_FragColor=color*(alpha*opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","\n#define MAX_LINE_DISTANCE 32767.0\n#define scale 0.015873016\nattribute vec2 a_pos_normal;attribute vec4 a_data;uniform mat4 u_matrix;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;uniform vec2 u_units_to_pixels;varying vec2 v_normal;varying vec2 v_width2;varying float v_gamma_scale;varying highp float v_lineprogress;\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;v_lineprogress=(floor(a_data.z/4.0)+a_data.w*64.0)*2.0/MAX_LINE_DISTANCE;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);vec4 projected_extrude=u_matrix*vec4(dist/u_ratio,0.0,0.0);gl_Position=u_matrix*vec4(pos+offset2/u_ratio,0.0,1.0)+projected_extrude;float extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length(projected_extrude.xy/gl_Position.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;v_width2=vec2(outset,inset);}"),hi=gi("uniform lowp float u_device_pixel_ratio;uniform vec2 u_texsize;uniform float u_fade;uniform mediump vec3 u_scale;uniform sampler2D u_image;varying vec2 v_normal;varying vec2 v_width2;varying float v_linesofar;varying float v_gamma_scale;varying float v_width;\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileZoomRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;vec2 pattern_size_a=vec2(display_size_a.x*fromScale/tileZoomRatio,display_size_a.y);vec2 pattern_size_b=vec2(display_size_b.x*toScale/tileZoomRatio,display_size_b.y);float aspect_a=display_size_a.y/v_width;float aspect_b=display_size_b.y/v_width;float dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);float x_a=mod(v_linesofar/pattern_size_a.x*aspect_a,1.0);float x_b=mod(v_linesofar/pattern_size_b.x*aspect_b,1.0);float y=0.5*v_normal.y+0.5;vec2 texel_size=1.0/u_texsize;vec2 pos_a=mix(pattern_tl_a*texel_size-texel_size,pattern_br_a*texel_size+texel_size,vec2(x_a,y));vec2 pos_b=mix(pattern_tl_b*texel_size-texel_size,pattern_br_b*texel_size+texel_size,vec2(x_b,y));vec4 color=mix(texture2D(u_image,pos_a),texture2D(u_image,pos_b),u_fade);gl_FragColor=color*alpha*opacity;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\n#define LINE_DISTANCE_SCALE 2.0\nattribute vec2 a_pos_normal;attribute vec4 a_data;uniform mat4 u_matrix;uniform vec2 u_units_to_pixels;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;varying vec2 v_normal;varying vec2 v_width2;varying float v_linesofar;varying float v_gamma_scale;varying float v_width;\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\n#pragma mapbox: define lowp vec4 pattern_from\n#pragma mapbox: define lowp vec4 pattern_to\n#pragma mapbox: define lowp float pixel_ratio_from\n#pragma mapbox: define lowp float pixel_ratio_to\nvoid main() {\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\n#pragma mapbox: initialize mediump vec4 pattern_from\n#pragma mapbox: initialize mediump vec4 pattern_to\n#pragma mapbox: initialize lowp float pixel_ratio_from\n#pragma mapbox: initialize lowp float pixel_ratio_to\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;float a_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*LINE_DISTANCE_SCALE;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);vec4 projected_extrude=u_matrix*vec4(dist/u_ratio,0.0,0.0);gl_Position=u_matrix*vec4(pos+offset2/u_ratio,0.0,1.0)+projected_extrude;float extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length(projected_extrude.xy/gl_Position.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;v_linesofar=a_linesofar;v_width2=vec2(outset,inset);v_width=floorwidth;}"),pi=gi("uniform lowp float u_device_pixel_ratio;uniform sampler2D u_image;uniform float u_sdfgamma;uniform float u_mix;varying vec2 v_normal;varying vec2 v_width2;varying vec2 v_tex_a;varying vec2 v_tex_b;varying float v_gamma_scale;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\nfloat dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);float sdfdist_a=texture2D(u_image,v_tex_a).a;float sdfdist_b=texture2D(u_image,v_tex_b).a;float sdfdist=mix(sdfdist_a,sdfdist_b,u_mix);alpha*=smoothstep(0.5-u_sdfgamma/floorwidth,0.5+u_sdfgamma/floorwidth,sdfdist);gl_FragColor=color*(alpha*opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","\n#define scale 0.015873016\n#define LINE_DISTANCE_SCALE 2.0\nattribute vec2 a_pos_normal;attribute vec4 a_data;uniform mat4 u_matrix;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;uniform vec2 u_patternscale_a;uniform float u_tex_y_a;uniform vec2 u_patternscale_b;uniform float u_tex_y_b;uniform vec2 u_units_to_pixels;varying vec2 v_normal;varying vec2 v_width2;varying vec2 v_tex_a;varying vec2 v_tex_b;varying float v_gamma_scale;\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\nvoid main() {\n#pragma mapbox: initialize highp vec4 color\n#pragma mapbox: initialize lowp float blur\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize mediump float gapwidth\n#pragma mapbox: initialize lowp float offset\n#pragma mapbox: initialize mediump float width\n#pragma mapbox: initialize lowp float floorwidth\nfloat ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=a_data.xy-128.0;float a_direction=mod(a_data.z,4.0)-1.0;float a_linesofar=(floor(a_data.z/4.0)+a_data.w*64.0)*LINE_DISTANCE_SCALE;vec2 pos=floor(a_pos_normal*0.5);mediump vec2 normal=a_pos_normal-2.0*pos;normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);vec4 projected_extrude=u_matrix*vec4(dist/u_ratio,0.0,0.0);gl_Position=u_matrix*vec4(pos+offset2/u_ratio,0.0,1.0)+projected_extrude;float extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length(projected_extrude.xy/gl_Position.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;v_tex_a=vec2(a_linesofar*u_patternscale_a.x/floorwidth,normal.y*u_patternscale_a.y+u_tex_y_a);v_tex_b=vec2(a_linesofar*u_patternscale_b.x/floorwidth,normal.y*u_patternscale_b.y+u_tex_y_b);v_width2=vec2(outset,inset);}"),di=gi("uniform float u_fade_t;uniform float u_opacity;uniform sampler2D u_image0;uniform sampler2D u_image1;varying vec2 v_pos0;varying vec2 v_pos1;uniform float u_brightness_low;uniform float u_brightness_high;uniform float u_saturation_factor;uniform float u_contrast_factor;uniform vec3 u_spin_weights;void main() {vec4 color0=texture2D(u_image0,v_pos0);vec4 color1=texture2D(u_image1,v_pos1);if (color0.a > 0.0) {color0.rgb=color0.rgb/color0.a;}if (color1.a > 0.0) {color1.rgb=color1.rgb/color1.a;}vec4 color=mix(color0,color1,u_fade_t);color.a*=u_opacity;vec3 rgb=color.rgb;rgb=vec3(dot(rgb,u_spin_weights.xyz),dot(rgb,u_spin_weights.zxy),dot(rgb,u_spin_weights.yzx));float average=(color.r+color.g+color.b)/3.0;rgb+=(average-rgb)*u_saturation_factor;rgb=(rgb-0.5)*u_contrast_factor+0.5;vec3 u_high_vec=vec3(u_brightness_low,u_brightness_low,u_brightness_low);vec3 u_low_vec=vec3(u_brightness_high,u_brightness_high,u_brightness_high);gl_FragColor=vec4(mix(u_high_vec,u_low_vec,rgb)*color.a,color.a);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","uniform mat4 u_matrix;uniform vec2 u_tl_parent;uniform float u_scale_parent;uniform float u_buffer_scale;attribute vec2 a_pos;attribute vec2 a_texture_pos;varying vec2 v_pos0;varying vec2 v_pos1;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);v_pos0=(((a_texture_pos/8192.0)-0.5)/u_buffer_scale )+0.5;v_pos1=(v_pos0*u_scale_parent)+u_tl_parent;}"),_i=gi("uniform sampler2D u_texture;varying vec2 v_tex;varying float v_fade_opacity;\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\nlowp float alpha=opacity*v_fade_opacity;gl_FragColor=texture2D(u_texture,v_tex)*alpha;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","const float PI=3.141592653589793;attribute vec4 a_pos_offset;attribute vec4 a_data;attribute vec4 a_pixeloffset;attribute vec3 a_projected_pos;attribute float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform highp float u_camera_to_center_distance;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform float u_fade_change;uniform mat4 u_matrix;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform vec2 u_texsize;varying vec2 v_tex;varying float v_fade_opacity;\n#pragma mapbox: define lowp float opacity\nvoid main() {\n#pragma mapbox: initialize lowp float opacity\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);vec2 a_pxoffset=a_pixeloffset.xy;vec2 a_minFontScale=a_pixeloffset.zw/256.0;highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec4 projectedPoint=u_matrix*vec4(a_pos,0,1);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=u_is_text ? size/24.0 : size;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=u_matrix*vec4(a_pos+vec2(1,0),0,1);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy,0.0,1.0);gl_Position=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*max(a_minFontScale,fontScale)+a_pxoffset/16.0),0.0,1.0);v_tex=a_tex/u_texsize;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;v_fade_opacity=max(0.0,min(1.0,fade_opacity[0]+fade_change));}"),fi=gi("#define SDF_PX 8.0\nuniform bool u_is_halo;uniform sampler2D u_texture;uniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;uniform bool u_is_text;varying vec2 v_data0;varying vec3 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nfloat EDGE_GAMMA=0.105/u_device_pixel_ratio;vec2 tex=v_data0.xy;float gamma_scale=v_data1.x;float size=v_data1.y;float fade_opacity=v_data1[2];float fontScale=u_is_text ? size/24.0 : size;lowp vec4 color=fill_color;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float buff=(256.0-64.0)/256.0;if (u_is_halo) {color=halo_color;gamma=(halo_blur*1.19/SDF_PX+EDGE_GAMMA)/(fontScale*u_gamma_scale);buff=(6.0-halo_width/fontScale)/SDF_PX;}lowp float dist=texture2D(u_texture,tex).a;highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(buff-gamma_scaled,buff+gamma_scaled,dist);gl_FragColor=color*(alpha*opacity*fade_opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","const float PI=3.141592653589793;attribute vec4 a_pos_offset;attribute vec4 a_data;attribute vec4 a_pixeloffset;attribute vec3 a_projected_pos;attribute float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform mat4 u_matrix;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform highp float u_camera_to_center_distance;uniform float u_fade_change;uniform vec2 u_texsize;varying vec2 v_data0;varying vec3 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);vec2 a_pxoffset=a_pixeloffset.xy;highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec4 projectedPoint=u_matrix*vec4(a_pos,0,1);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=u_is_text ? size/24.0 : size;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=u_matrix*vec4(a_pos+vec2(1,0),0,1);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy,0.0,1.0);gl_Position=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*fontScale+a_pxoffset),0.0,1.0);float gamma_scale=gl_Position.w;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float interpolated_fade_opacity=max(0.0,min(1.0,fade_opacity[0]+fade_change));v_data0=a_tex/u_texsize;v_data1=vec3(gamma_scale,size,interpolated_fade_opacity);}"),mi=gi("#define SDF_PX 8.0\n#define SDF 1.0\n#define ICON 0.0\nuniform bool u_is_halo;uniform sampler2D u_texture;uniform sampler2D u_texture_icon;uniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;varying vec4 v_data0;varying vec4 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nfloat fade_opacity=v_data1[2];if (v_data1.w==ICON) {vec2 tex_icon=v_data0.zw;lowp float alpha=opacity*fade_opacity;gl_FragColor=texture2D(u_texture_icon,tex_icon)*alpha;\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\nreturn;}vec2 tex=v_data0.xy;float EDGE_GAMMA=0.105/u_device_pixel_ratio;float gamma_scale=v_data1.x;float size=v_data1.y;float fontScale=size/24.0;lowp vec4 color=fill_color;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float buff=(256.0-64.0)/256.0;if (u_is_halo) {color=halo_color;gamma=(halo_blur*1.19/SDF_PX+EDGE_GAMMA)/(fontScale*u_gamma_scale);buff=(6.0-halo_width/fontScale)/SDF_PX;}lowp float dist=texture2D(u_texture,tex).a;highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(buff-gamma_scaled,buff+gamma_scaled,dist);gl_FragColor=color*(alpha*opacity*fade_opacity);\n#ifdef OVERDRAW_INSPECTOR\ngl_FragColor=vec4(1.0);\n#endif\n}","const float PI=3.141592653589793;attribute vec4 a_pos_offset;attribute vec4 a_data;attribute vec3 a_projected_pos;attribute float a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform mat4 u_matrix;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform highp float u_camera_to_center_distance;uniform float u_fade_change;uniform vec2 u_texsize;uniform vec2 u_texsize_icon;varying vec4 v_data0;varying vec4 v_data1;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\nvoid main() {\n#pragma mapbox: initialize highp vec4 fill_color\n#pragma mapbox: initialize highp vec4 halo_color\n#pragma mapbox: initialize lowp float opacity\n#pragma mapbox: initialize lowp float halo_width\n#pragma mapbox: initialize lowp float halo_blur\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=a_data.xy;vec2 a_size=a_data.zw;float a_size_min=floor(a_size[0]*0.5);float is_sdf=a_size[0]-2.0*a_size_min;highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec4 projectedPoint=u_matrix*vec4(a_pos,0,1);highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);size*=perspective_ratio;float fontScale=size/24.0;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=u_matrix*vec4(a_pos+vec2(1,0),0,1);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy,0.0,1.0);gl_Position=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*fontScale),0.0,1.0);float gamma_scale=gl_Position.w;vec2 fade_opacity=unpack_opacity(a_fade_opacity);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float interpolated_fade_opacity=max(0.0,min(1.0,fade_opacity[0]+fade_change));v_data0.xy=a_tex/u_texsize;v_data0.zw=a_tex/u_texsize_icon;v_data1=vec4(gamma_scale,size,interpolated_fade_opacity,is_sdf);}");function gi(t,e){var i=/#pragma mapbox: ([\w]+) ([\w]+) ([\w]+) ([\w]+)/g,o={};return {fragmentSource:t=t.replace(i,(function(t,e,i,r,a){return o[a]=!0,"define"===e?"\n#ifndef HAS_UNIFORM_u_"+a+"\nvarying "+i+" "+r+" "+a+";\n#else\nuniform "+i+" "+r+" u_"+a+";\n#endif\n":"\n#ifdef HAS_UNIFORM_u_"+a+"\n "+i+" "+r+" "+a+" = u_"+a+";\n#endif\n"})),vertexSource:e=e.replace(i,(function(t,e,i,r,a){var n="float"===r?"vec2":"vec4",s=a.match(/color/)?"color":n;return o[a]?"define"===e?"\n#ifndef HAS_UNIFORM_u_"+a+"\nuniform lowp float u_"+a+"_t;\nattribute "+i+" "+n+" a_"+a+";\nvarying "+i+" "+r+" "+a+";\n#else\nuniform "+i+" "+r+" u_"+a+";\n#endif\n":"vec4"===s?"\n#ifndef HAS_UNIFORM_u_"+a+"\n "+a+" = a_"+a+";\n#else\n "+i+" "+r+" "+a+" = u_"+a+";\n#endif\n":"\n#ifndef HAS_UNIFORM_u_"+a+"\n "+a+" = unpack_mix_"+s+"(a_"+a+", u_"+a+"_t);\n#else\n "+i+" "+r+" "+a+" = u_"+a+";\n#endif\n":"define"===e?"\n#ifndef HAS_UNIFORM_u_"+a+"\nuniform lowp float u_"+a+"_t;\nattribute "+i+" "+n+" a_"+a+";\n#else\nuniform "+i+" "+r+" u_"+a+";\n#endif\n":"vec4"===s?"\n#ifndef HAS_UNIFORM_u_"+a+"\n "+i+" "+r+" "+a+" = a_"+a+";\n#else\n "+i+" "+r+" "+a+" = u_"+a+";\n#endif\n":"\n#ifndef HAS_UNIFORM_u_"+a+"\n "+i+" "+r+" "+a+" = unpack_mix_"+s+"(a_"+a+", u_"+a+"_t);\n#else\n "+i+" "+r+" "+a+" = u_"+a+";\n#endif\n"}))}}var vi=Object.freeze({__proto__:null,prelude:Ge,background:We,backgroundPattern:Xe,circle:He,clippingMask:Ke,heatmap:Ye,heatmapTexture:Je,collisionBox:Qe,collisionCircle:$e,debug:ti,fill:ei,fillOutline:ii,fillOutlinePattern:oi,fillPattern:ri,fillExtrusion:ai,fillExtrusionPattern:ni,hillshadePrepare:si,hillshade:li,line:ci,lineGradient:ui,linePattern:hi,lineSDF:pi,raster:di,symbolIcon:_i,symbolSDF:fi,symbolTextAndIcon:mi}),yi=function(){this.boundProgram=null,this.boundLayoutVertexBuffer=null,this.boundPaintVertexBuffers=[],this.boundIndexBuffer=null,this.boundVertexOffset=null,this.boundDynamicVertexBuffer=null,this.vao=null;};yi.prototype.bind=function(t,e,i,o,r,a,n,s){this.context=t;for(var l=this.boundPaintVertexBuffers.length!==o.length,c=0;!l&&c>16,s>>16],u_pixel_coord_lower:[65535&n,65535&s]}}xi.prototype.draw=function(t,e,i,o,r,a,n,s,l,c,u,h,p,d,_,f){var m,g=t.gl;if(!this.failedToCreate){for(var v in t.program.set(this.program),t.setDepthMode(i),t.setStencilMode(o),t.setColorMode(r),t.setCullFace(a),this.fixedUniforms)this.fixedUniforms[v].set(n[v]);d&&d.setUniforms(t,this.binderUniforms,h,{zoom:p});for(var y=(m={},m[g.LINES]=2,m[g.TRIANGLES]=3,m[g.LINE_STRIP]=1,m)[e],x=0,b=u.get();x0?1-1/(1.001-n):-n),u_contrast_factor:(a=r.paint.get("raster-contrast"),a>0?1/(1-a):1+a),u_spin_weights:Zi(r.paint.get("raster-hue-rotate"))};var a,n;};function Zi(t){t*=Math.PI/180;var e=Math.sin(t),i=Math.cos(t);return [(2*i+1)/3,(-Math.sqrt(3)*e-i+1)/3,(Math.sqrt(3)*e-i+1)/3]}var ji,qi=function(t,e,i,o,r,a,n,s,l,c){var u=r.transform;return {u_is_size_zoom_constant:+("constant"===t||"source"===t),u_is_size_feature_constant:+("constant"===t||"camera"===t),u_size_t:e?e.uSizeT:0,u_size:e?e.uSize:0,u_camera_to_center_distance:u.cameraToCenterDistance,u_pitch:u.pitch/360*2*Math.PI,u_rotate_symbol:+i,u_aspect_ratio:u.width/u.height,u_fade_change:r.options.fadeDuration?r.symbolFadeChange:1,u_matrix:a,u_label_plane_matrix:n,u_coord_matrix:s,u_is_text:+l,u_pitch_with_map:+o,u_texsize:c,u_texture:0}},Vi=function(e,i,o,r,a,n,s,l,c,u,h){var p=a.transform;return t.extend(qi(e,i,o,r,a,n,s,l,c,u),{u_gamma_scale:r?Math.cos(p._pitch)*p.cameraToCenterDistance:1,u_device_pixel_ratio:t.browser.devicePixelRatio,u_is_halo:+h})},Gi=function(e,i,o,r,a,n,s,l,c,u){return t.extend(Vi(e,i,o,r,a,n,s,l,!0,c,!0),{u_texsize_icon:u,u_texture_icon:1})},Wi=function(t,e,i){return {u_matrix:t,u_opacity:e,u_color:i}},Xi=function(e,i,o,r,a,n){return t.extend(function(t,e,i,o){var r=i.imageManager.getPattern(t.from.toString()),a=i.imageManager.getPattern(t.to.toString()),n=i.imageManager.getPixelSize(),s=n.width,l=n.height,c=Math.pow(2,o.tileID.overscaledZ),u=o.tileSize*Math.pow(2,i.transform.tileZoom)/c,h=u*(o.tileID.canonical.x+o.tileID.wrap*c),p=u*o.tileID.canonical.y;return {u_image:0,u_pattern_tl_a:r.tl,u_pattern_br_a:r.br,u_pattern_tl_b:a.tl,u_pattern_br_b:a.br,u_texsize:[s,l],u_mix:e.t,u_pattern_size_a:r.displaySize,u_pattern_size_b:a.displaySize,u_scale_a:e.fromScale,u_scale_b:e.toScale,u_tile_units_to_pixels:1/pe(o,1,i.transform.tileZoom),u_pixel_coord_upper:[h>>16,p>>16],u_pixel_coord_lower:[65535&h,65535&p]}}(r,n,o,a),{u_matrix:e,u_opacity:i})},Hi={fillExtrusion:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_lightpos:new t.Uniform3f(e,i.u_lightpos),u_lightintensity:new t.Uniform1f(e,i.u_lightintensity),u_lightcolor:new t.Uniform3f(e,i.u_lightcolor),u_vertical_gradient:new t.Uniform1f(e,i.u_vertical_gradient),u_opacity:new t.Uniform1f(e,i.u_opacity)}},fillExtrusionPattern:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_lightpos:new t.Uniform3f(e,i.u_lightpos),u_lightintensity:new t.Uniform1f(e,i.u_lightintensity),u_lightcolor:new t.Uniform3f(e,i.u_lightcolor),u_vertical_gradient:new t.Uniform1f(e,i.u_vertical_gradient),u_height_factor:new t.Uniform1f(e,i.u_height_factor),u_image:new t.Uniform1i(e,i.u_image),u_texsize:new t.Uniform2f(e,i.u_texsize),u_pixel_coord_upper:new t.Uniform2f(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.Uniform2f(e,i.u_pixel_coord_lower),u_scale:new t.Uniform3f(e,i.u_scale),u_fade:new t.Uniform1f(e,i.u_fade),u_opacity:new t.Uniform1f(e,i.u_opacity)}},fill:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix)}},fillPattern:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_image:new t.Uniform1i(e,i.u_image),u_texsize:new t.Uniform2f(e,i.u_texsize),u_pixel_coord_upper:new t.Uniform2f(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.Uniform2f(e,i.u_pixel_coord_lower),u_scale:new t.Uniform3f(e,i.u_scale),u_fade:new t.Uniform1f(e,i.u_fade)}},fillOutline:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_world:new t.Uniform2f(e,i.u_world)}},fillOutlinePattern:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_world:new t.Uniform2f(e,i.u_world),u_image:new t.Uniform1i(e,i.u_image),u_texsize:new t.Uniform2f(e,i.u_texsize),u_pixel_coord_upper:new t.Uniform2f(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.Uniform2f(e,i.u_pixel_coord_lower),u_scale:new t.Uniform3f(e,i.u_scale),u_fade:new t.Uniform1f(e,i.u_fade)}},circle:function(e,i){return {u_camera_to_center_distance:new t.Uniform1f(e,i.u_camera_to_center_distance),u_scale_with_map:new t.Uniform1i(e,i.u_scale_with_map),u_pitch_with_map:new t.Uniform1i(e,i.u_pitch_with_map),u_extrude_scale:new t.Uniform2f(e,i.u_extrude_scale),u_device_pixel_ratio:new t.Uniform1f(e,i.u_device_pixel_ratio),u_matrix:new t.UniformMatrix4f(e,i.u_matrix)}},collisionBox:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_camera_to_center_distance:new t.Uniform1f(e,i.u_camera_to_center_distance),u_pixels_to_tile_units:new t.Uniform1f(e,i.u_pixels_to_tile_units),u_extrude_scale:new t.Uniform2f(e,i.u_extrude_scale),u_overscale_factor:new t.Uniform1f(e,i.u_overscale_factor)}},collisionCircle:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_inv_matrix:new t.UniformMatrix4f(e,i.u_inv_matrix),u_camera_to_center_distance:new t.Uniform1f(e,i.u_camera_to_center_distance),u_viewport_size:new t.Uniform2f(e,i.u_viewport_size)}},debug:function(e,i){return {u_color:new t.UniformColor(e,i.u_color),u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_overlay:new t.Uniform1i(e,i.u_overlay),u_overlay_scale:new t.Uniform1f(e,i.u_overlay_scale)}},clippingMask:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix)}},heatmap:function(e,i){return {u_extrude_scale:new t.Uniform1f(e,i.u_extrude_scale),u_intensity:new t.Uniform1f(e,i.u_intensity),u_matrix:new t.UniformMatrix4f(e,i.u_matrix)}},heatmapTexture:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_world:new t.Uniform2f(e,i.u_world),u_image:new t.Uniform1i(e,i.u_image),u_color_ramp:new t.Uniform1i(e,i.u_color_ramp),u_opacity:new t.Uniform1f(e,i.u_opacity)}},hillshade:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_image:new t.Uniform1i(e,i.u_image),u_latrange:new t.Uniform2f(e,i.u_latrange),u_light:new t.Uniform2f(e,i.u_light),u_shadow:new t.UniformColor(e,i.u_shadow),u_highlight:new t.UniformColor(e,i.u_highlight),u_accent:new t.UniformColor(e,i.u_accent)}},hillshadePrepare:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_image:new t.Uniform1i(e,i.u_image),u_dimension:new t.Uniform2f(e,i.u_dimension),u_zoom:new t.Uniform1f(e,i.u_zoom),u_maxzoom:new t.Uniform1f(e,i.u_maxzoom),u_unpack:new t.Uniform4f(e,i.u_unpack)}},line:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_ratio:new t.Uniform1f(e,i.u_ratio),u_device_pixel_ratio:new t.Uniform1f(e,i.u_device_pixel_ratio),u_units_to_pixels:new t.Uniform2f(e,i.u_units_to_pixels)}},lineGradient:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_ratio:new t.Uniform1f(e,i.u_ratio),u_device_pixel_ratio:new t.Uniform1f(e,i.u_device_pixel_ratio),u_units_to_pixels:new t.Uniform2f(e,i.u_units_to_pixels),u_image:new t.Uniform1i(e,i.u_image)}},linePattern:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_texsize:new t.Uniform2f(e,i.u_texsize),u_ratio:new t.Uniform1f(e,i.u_ratio),u_device_pixel_ratio:new t.Uniform1f(e,i.u_device_pixel_ratio),u_image:new t.Uniform1i(e,i.u_image),u_units_to_pixels:new t.Uniform2f(e,i.u_units_to_pixels),u_scale:new t.Uniform3f(e,i.u_scale),u_fade:new t.Uniform1f(e,i.u_fade)}},lineSDF:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_ratio:new t.Uniform1f(e,i.u_ratio),u_device_pixel_ratio:new t.Uniform1f(e,i.u_device_pixel_ratio),u_units_to_pixels:new t.Uniform2f(e,i.u_units_to_pixels),u_patternscale_a:new t.Uniform2f(e,i.u_patternscale_a),u_patternscale_b:new t.Uniform2f(e,i.u_patternscale_b),u_sdfgamma:new t.Uniform1f(e,i.u_sdfgamma),u_image:new t.Uniform1i(e,i.u_image),u_tex_y_a:new t.Uniform1f(e,i.u_tex_y_a),u_tex_y_b:new t.Uniform1f(e,i.u_tex_y_b),u_mix:new t.Uniform1f(e,i.u_mix)}},raster:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_tl_parent:new t.Uniform2f(e,i.u_tl_parent),u_scale_parent:new t.Uniform1f(e,i.u_scale_parent),u_buffer_scale:new t.Uniform1f(e,i.u_buffer_scale),u_fade_t:new t.Uniform1f(e,i.u_fade_t),u_opacity:new t.Uniform1f(e,i.u_opacity),u_image0:new t.Uniform1i(e,i.u_image0),u_image1:new t.Uniform1i(e,i.u_image1),u_brightness_low:new t.Uniform1f(e,i.u_brightness_low),u_brightness_high:new t.Uniform1f(e,i.u_brightness_high),u_saturation_factor:new t.Uniform1f(e,i.u_saturation_factor),u_contrast_factor:new t.Uniform1f(e,i.u_contrast_factor),u_spin_weights:new t.Uniform3f(e,i.u_spin_weights)}},symbolIcon:function(e,i){return {u_is_size_zoom_constant:new t.Uniform1i(e,i.u_is_size_zoom_constant),u_is_size_feature_constant:new t.Uniform1i(e,i.u_is_size_feature_constant),u_size_t:new t.Uniform1f(e,i.u_size_t),u_size:new t.Uniform1f(e,i.u_size),u_camera_to_center_distance:new t.Uniform1f(e,i.u_camera_to_center_distance),u_pitch:new t.Uniform1f(e,i.u_pitch),u_rotate_symbol:new t.Uniform1i(e,i.u_rotate_symbol),u_aspect_ratio:new t.Uniform1f(e,i.u_aspect_ratio),u_fade_change:new t.Uniform1f(e,i.u_fade_change),u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_label_plane_matrix:new t.UniformMatrix4f(e,i.u_label_plane_matrix),u_coord_matrix:new t.UniformMatrix4f(e,i.u_coord_matrix),u_is_text:new t.Uniform1i(e,i.u_is_text),u_pitch_with_map:new t.Uniform1i(e,i.u_pitch_with_map),u_texsize:new t.Uniform2f(e,i.u_texsize),u_texture:new t.Uniform1i(e,i.u_texture)}},symbolSDF:function(e,i){return {u_is_size_zoom_constant:new t.Uniform1i(e,i.u_is_size_zoom_constant),u_is_size_feature_constant:new t.Uniform1i(e,i.u_is_size_feature_constant),u_size_t:new t.Uniform1f(e,i.u_size_t),u_size:new t.Uniform1f(e,i.u_size),u_camera_to_center_distance:new t.Uniform1f(e,i.u_camera_to_center_distance),u_pitch:new t.Uniform1f(e,i.u_pitch),u_rotate_symbol:new t.Uniform1i(e,i.u_rotate_symbol),u_aspect_ratio:new t.Uniform1f(e,i.u_aspect_ratio),u_fade_change:new t.Uniform1f(e,i.u_fade_change),u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_label_plane_matrix:new t.UniformMatrix4f(e,i.u_label_plane_matrix),u_coord_matrix:new t.UniformMatrix4f(e,i.u_coord_matrix),u_is_text:new t.Uniform1i(e,i.u_is_text),u_pitch_with_map:new t.Uniform1i(e,i.u_pitch_with_map),u_texsize:new t.Uniform2f(e,i.u_texsize),u_texture:new t.Uniform1i(e,i.u_texture),u_gamma_scale:new t.Uniform1f(e,i.u_gamma_scale),u_device_pixel_ratio:new t.Uniform1f(e,i.u_device_pixel_ratio),u_is_halo:new t.Uniform1i(e,i.u_is_halo)}},symbolTextAndIcon:function(e,i){return {u_is_size_zoom_constant:new t.Uniform1i(e,i.u_is_size_zoom_constant),u_is_size_feature_constant:new t.Uniform1i(e,i.u_is_size_feature_constant),u_size_t:new t.Uniform1f(e,i.u_size_t),u_size:new t.Uniform1f(e,i.u_size),u_camera_to_center_distance:new t.Uniform1f(e,i.u_camera_to_center_distance),u_pitch:new t.Uniform1f(e,i.u_pitch),u_rotate_symbol:new t.Uniform1i(e,i.u_rotate_symbol),u_aspect_ratio:new t.Uniform1f(e,i.u_aspect_ratio),u_fade_change:new t.Uniform1f(e,i.u_fade_change),u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_label_plane_matrix:new t.UniformMatrix4f(e,i.u_label_plane_matrix),u_coord_matrix:new t.UniformMatrix4f(e,i.u_coord_matrix),u_is_text:new t.Uniform1i(e,i.u_is_text),u_pitch_with_map:new t.Uniform1i(e,i.u_pitch_with_map),u_texsize:new t.Uniform2f(e,i.u_texsize),u_texsize_icon:new t.Uniform2f(e,i.u_texsize_icon),u_texture:new t.Uniform1i(e,i.u_texture),u_texture_icon:new t.Uniform1i(e,i.u_texture_icon),u_gamma_scale:new t.Uniform1f(e,i.u_gamma_scale),u_device_pixel_ratio:new t.Uniform1f(e,i.u_device_pixel_ratio),u_is_halo:new t.Uniform1i(e,i.u_is_halo)}},background:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_opacity:new t.Uniform1f(e,i.u_opacity),u_color:new t.UniformColor(e,i.u_color)}},backgroundPattern:function(e,i){return {u_matrix:new t.UniformMatrix4f(e,i.u_matrix),u_opacity:new t.Uniform1f(e,i.u_opacity),u_image:new t.Uniform1i(e,i.u_image),u_pattern_tl_a:new t.Uniform2f(e,i.u_pattern_tl_a),u_pattern_br_a:new t.Uniform2f(e,i.u_pattern_br_a),u_pattern_tl_b:new t.Uniform2f(e,i.u_pattern_tl_b),u_pattern_br_b:new t.Uniform2f(e,i.u_pattern_br_b),u_texsize:new t.Uniform2f(e,i.u_texsize),u_mix:new t.Uniform1f(e,i.u_mix),u_pattern_size_a:new t.Uniform2f(e,i.u_pattern_size_a),u_pattern_size_b:new t.Uniform2f(e,i.u_pattern_size_b),u_scale_a:new t.Uniform1f(e,i.u_scale_a),u_scale_b:new t.Uniform1f(e,i.u_scale_b),u_pixel_coord_upper:new t.Uniform2f(e,i.u_pixel_coord_upper),u_pixel_coord_lower:new t.Uniform2f(e,i.u_pixel_coord_lower),u_tile_units_to_pixels:new t.Uniform1f(e,i.u_tile_units_to_pixels)}}};function Ki(e,i,o,r,a,n,s){for(var l=e.context,c=l.gl,u=e.useProgram("collisionBox"),h=[],p=0,d=0,_=0;_0){var b=t.create(),w=v;t.mul(b,g.placementInvProjMatrix,e.transform.glCoordMatrix),t.mul(b,b,g.placementViewportMatrix),h.push({circleArray:x,circleOffset:d,transform:w,invTransform:b}),d=p+=x.length/4;}y&&u.draw(l,c.LINES,It.disabled,Pt.disabled,e.colorModeForRenderPass(),Ct.disabled,zi(v,e.transform,m),o.id,y.layoutVertexBuffer,y.indexBuffer,y.segments,null,e.transform.zoom,null,null,y.collisionVertexBuffer);}}if(s&&h.length){var T=e.useProgram("collisionCircle"),E=new t.StructArrayLayout2f1f2i16;E.resize(4*p),E._trim();for(var I=0,P=0,S=h;P=0&&(f[g.associatedIconIndex]={shiftedAnchor:E,angle:I});}else ce(g.numGlyphs,d);}if(h){_.clear();for(var S=e.icon.placedSymbolArray,C=0;C0){var s=t.browser.now(),l=(s-e.timeAdded)/n,c=i?(s-i.timeAdded)/n:-1,u=o.getSource(),h=a.coveringZoomLevel({tileSize:u.tileSize,roundZoom:u.roundZoom}),p=!i||Math.abs(i.tileID.overscaledZ-h)>Math.abs(e.tileID.overscaledZ-h),d=p&&e.refreshedUponExpiration?1:t.clamp(p?l:1-c,0,1);return e.refreshedUponExpiration&&l>=1&&(e.refreshedUponExpiration=!1),i?{opacity:1,mix:1-d}:{opacity:d,mix:0}}return {opacity:1,mix:0}}var so=new t.Color(1,0,0,1),lo=new t.Color(0,1,0,1),co=new t.Color(0,0,1,1),uo=new t.Color(1,0,1,1),ho=new t.Color(0,1,1,1);function po(t,e,i,o){fo(t,0,e+i/2,t.transform.width,i,o);}function _o(t,e,i,o){fo(t,e-i/2,0,i,t.transform.height,o);}function fo(e,i,o,r,a,n){var s=e.context,l=s.gl;l.enable(l.SCISSOR_TEST),l.scissor(i*t.browser.devicePixelRatio,o*t.browser.devicePixelRatio,r*t.browser.devicePixelRatio,a*t.browser.devicePixelRatio),s.clear({color:n}),l.disable(l.SCISSOR_TEST);}function mo(e,i,o){var r=e.context,a=r.gl,n=o.posMatrix,s=e.useProgram("debug"),l=It.disabled,c=Pt.disabled,u=e.colorModeForRenderPass();r.activeTexture.set(a.TEXTURE0),e.emptyTexture.bind(a.LINEAR,a.CLAMP_TO_EDGE),s.draw(r,a.LINE_STRIP,l,c,u,Ct.disabled,Mi(n,t.Color.red),"$debug",e.debugBuffer,e.tileBorderIndexBuffer,e.debugSegments);var h=i.getTileByID(o.key).latestRawTileData,p=Math.floor((h&&h.byteLength||0)/1024),d=i.getTile(o).tileSize,_=512/Math.min(d,512)*(o.overscaledZ/e.transform.zoom)*.5,f=o.canonical.toString();o.overscaledZ!==o.canonical.z&&(f+=" => "+o.overscaledZ),function(t,e){t.initDebugOverlayCanvas();var i=t.debugOverlayCanvas,o=t.context.gl,r=t.debugOverlayCanvas.getContext("2d");r.clearRect(0,0,i.width,i.height),r.shadowColor="white",r.shadowBlur=2,r.lineWidth=1.5,r.strokeStyle="white",r.textBaseline="top",r.font="bold 36px Open Sans, sans-serif",r.fillText(e,5,5),r.strokeText(e,5,5),t.debugOverlayTexture.update(i),t.debugOverlayTexture.bind(o.LINEAR,o.CLAMP_TO_EDGE);}(e,f+" "+p+"kb"),s.draw(r,a.TRIANGLES,l,c,St.alphaBlended,Ct.disabled,Mi(n,t.Color.transparent,_),"$debug",e.debugBuffer,e.quadTriangleIndexBuffer,e.debugSegments);}var go={symbol:function(e,i,o,r,a){if("translucent"===e.renderPass){var n=Pt.disabled,s=e.colorModeForRenderPass();o.layout.get("text-variable-anchor")&&function(e,i,o,r,a,n,s){for(var l=i.transform,c="map"===a,u="map"===n,h=0,p=e;h256&&this.clearStencil(),i.setColorMode(St.disabled),i.setDepthMode(It.disabled);var r=this.useProgram("clippingMask");this._tileClippingMaskIDs={};for(var a=0,n=e;a256&&this.clearStencil();var t=this.nextStencilID++,e=this.context.gl;return new Pt({func:e.NOTEQUAL,mask:255},t,255,e.KEEP,e.KEEP,e.REPLACE)},vo.prototype.stencilModeForClipping=function(t){var e=this.context.gl;return new Pt({func:e.EQUAL,mask:255},this._tileClippingMaskIDs[t.key],0,e.KEEP,e.KEEP,e.REPLACE)},vo.prototype.stencilConfigForOverlap=function(t){var e,i=this.context.gl,o=t.sort((function(t,e){return e.overscaledZ-t.overscaledZ})),r=o[o.length-1].overscaledZ,a=o[0].overscaledZ-r+1;if(a>1){this.currentStencilSource=void 0,this.nextStencilID+a>256&&this.clearStencil();for(var n={},s=0;s=0;this.currentLayer--){var x=this.style._layers[r[this.currentLayer]],b=a[x.source],w=u[x.source];this._renderTileClippingMasks(x,w),this.renderLayer(this,b,x,w);}for(this.renderPass="translucent",this.currentLayer=0;this.currentLayer0?e.pop():null},vo.prototype.isPatternMissing=function(t){if(!t)return !1;if(!t.from||!t.to)return !0;var e=this.imageManager.getPattern(t.from.toString()),i=this.imageManager.getPattern(t.to.toString());return !e||!i},vo.prototype.useProgram=function(t,e){this.cache=this.cache||{};var i=""+t+(e?e.cacheKey:"")+(this._showOverdrawInspector?"/overdraw":"");return this.cache[i]||(this.cache[i]=new xi(this.context,vi[t],e,Hi[t],this._showOverdrawInspector)),this.cache[i]},vo.prototype.setCustomLayerDefaults=function(){this.context.unbindVAO(),this.context.cullFace.setDefault(),this.context.activeTexture.setDefault(),this.context.pixelStoreUnpack.setDefault(),this.context.pixelStoreUnpackPremultiplyAlpha.setDefault(),this.context.pixelStoreUnpackFlipY.setDefault();},vo.prototype.setBaseState=function(){var t=this.context.gl;this.context.cullFace.set(!1),this.context.viewport.set([0,0,this.width,this.height]),this.context.blendEquation.set(t.FUNC_ADD);},vo.prototype.initDebugOverlayCanvas=function(){null==this.debugOverlayCanvas&&(this.debugOverlayCanvas=t.window.document.createElement("canvas"),this.debugOverlayCanvas.width=512,this.debugOverlayCanvas.height=512,this.debugOverlayTexture=new t.Texture(this.context,this.debugOverlayCanvas,this.context.gl.RGBA));},vo.prototype.destroy=function(){this.emptyTexture.destroy(),this.debugOverlayTexture&&this.debugOverlayTexture.destroy();};var yo=function(t,e){this.points=t,this.planes=e;};yo.fromInvProjectionMatrix=function(e,i,o){var r=Math.pow(2,o),a=[[-1,1,-1,1],[1,1,-1,1],[1,-1,-1,1],[-1,-1,-1,1],[-1,1,1,1],[1,1,1,1],[1,-1,1,1],[-1,-1,1,1]].map((function(i){return t.transformMat4([],i,e)})).map((function(e){return t.scale$1([],e,1/e[3]/i*r)})),n=[[0,1,2],[6,5,4],[0,3,7],[2,1,5],[3,2,6],[0,4,5]].map((function(e){var i=t.sub([],a[e[0]],a[e[1]]),o=t.sub([],a[e[2]],a[e[1]]),r=t.normalize([],t.cross([],i,o)),n=-t.dot(r,a[e[1]]);return r.concat(n)}));return new yo(a,n)};var xo=function(e,i){this.min=e,this.max=i,this.center=t.scale$2([],t.add([],this.min,this.max),.5);};xo.prototype.quadrant=function(e){for(var i=[e%2==0,e<2],o=t.clone$2(this.min),r=t.clone$2(this.max),a=0;a=0;if(0===n)return 0;n!==i.length&&(o=!1);}if(o)return 2;for(var l=0;l<3;l++){for(var c=Number.MAX_VALUE,u=-Number.MAX_VALUE,h=0;hthis.max[l]-this.min[l])return 0}return 1};var bo=function(t,e,i,o){if(void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=0),void 0===o&&(o=0),isNaN(t)||t<0||isNaN(e)||e<0||isNaN(i)||i<0||isNaN(o)||o<0)throw new Error("Invalid value for edge-insets, top, bottom, left and right must all be numbers");this.top=t,this.bottom=e,this.left=i,this.right=o;};bo.prototype.interpolate=function(e,i,o){return null!=i.top&&null!=e.top&&(this.top=t.number(e.top,i.top,o)),null!=i.bottom&&null!=e.bottom&&(this.bottom=t.number(e.bottom,i.bottom,o)),null!=i.left&&null!=e.left&&(this.left=t.number(e.left,i.left,o)),null!=i.right&&null!=e.right&&(this.right=t.number(e.right,i.right,o)),this},bo.prototype.getCenter=function(e,i){var o=t.clamp((this.left+e-this.right)/2,0,e),r=t.clamp((this.top+i-this.bottom)/2,0,i);return new t.Point(o,r)},bo.prototype.equals=function(t){return this.top===t.top&&this.bottom===t.bottom&&this.left===t.left&&this.right===t.right},bo.prototype.clone=function(){return new bo(this.top,this.bottom,this.left,this.right)},bo.prototype.toJSON=function(){return {top:this.top,bottom:this.bottom,left:this.left,right:this.right}};var wo=function(e,i,o,r,a){this.tileSize=512,this.maxValidLatitude=85.051129,this._renderWorldCopies=void 0===a||a,this._minZoom=e||0,this._maxZoom=i||22,this._minPitch=null==o?0:o,this._maxPitch=null==r?60:r,this.setMaxBounds(),this.width=0,this.height=0,this._center=new t.LngLat(0,0),this.zoom=0,this.angle=0,this._fov=.6435011087932844,this._pitch=0,this._unmodified=!0,this._edgeInsets=new bo,this._posMatrixCache={},this._alignedPosMatrixCache={};},To={minZoom:{configurable:!0},maxZoom:{configurable:!0},minPitch:{configurable:!0},maxPitch:{configurable:!0},renderWorldCopies:{configurable:!0},worldSize:{configurable:!0},centerOffset:{configurable:!0},size:{configurable:!0},bearing:{configurable:!0},pitch:{configurable:!0},fov:{configurable:!0},zoom:{configurable:!0},center:{configurable:!0},padding:{configurable:!0},centerPoint:{configurable:!0},unmodified:{configurable:!0},point:{configurable:!0}};wo.prototype.clone=function(){var t=new wo(this._minZoom,this._maxZoom,this._minPitch,this.maxPitch,this._renderWorldCopies);return t.tileSize=this.tileSize,t.latRange=this.latRange,t.width=this.width,t.height=this.height,t._center=this._center,t.zoom=this.zoom,t.angle=this.angle,t._fov=this._fov,t._pitch=this._pitch,t._unmodified=this._unmodified,t._edgeInsets=this._edgeInsets.clone(),t._calcMatrices(),t},To.minZoom.get=function(){return this._minZoom},To.minZoom.set=function(t){this._minZoom!==t&&(this._minZoom=t,this.zoom=Math.max(this.zoom,t));},To.maxZoom.get=function(){return this._maxZoom},To.maxZoom.set=function(t){this._maxZoom!==t&&(this._maxZoom=t,this.zoom=Math.min(this.zoom,t));},To.minPitch.get=function(){return this._minPitch},To.minPitch.set=function(t){this._minPitch!==t&&(this._minPitch=t,this.pitch=Math.max(this.pitch,t));},To.maxPitch.get=function(){return this._maxPitch},To.maxPitch.set=function(t){this._maxPitch!==t&&(this._maxPitch=t,this.pitch=Math.min(this.pitch,t));},To.renderWorldCopies.get=function(){return this._renderWorldCopies},To.renderWorldCopies.set=function(t){void 0===t?t=!0:null===t&&(t=!1),this._renderWorldCopies=t;},To.worldSize.get=function(){return this.tileSize*this.scale},To.centerOffset.get=function(){return this.centerPoint._sub(this.size._div(2))},To.size.get=function(){return new t.Point(this.width,this.height)},To.bearing.get=function(){return -this.angle/Math.PI*180},To.bearing.set=function(e){var i=-t.wrap(e,-180,180)*Math.PI/180;this.angle!==i&&(this._unmodified=!1,this.angle=i,this._calcMatrices(),this.rotationMatrix=t.create$2(),t.rotate(this.rotationMatrix,this.rotationMatrix,this.angle));},To.pitch.get=function(){return this._pitch/Math.PI*180},To.pitch.set=function(e){var i=t.clamp(e,this.minPitch,this.maxPitch)/180*Math.PI;this._pitch!==i&&(this._unmodified=!1,this._pitch=i,this._calcMatrices());},To.fov.get=function(){return this._fov/Math.PI*180},To.fov.set=function(t){t=Math.max(.01,Math.min(60,t)),this._fov!==t&&(this._unmodified=!1,this._fov=t/180*Math.PI,this._calcMatrices());},To.zoom.get=function(){return this._zoom},To.zoom.set=function(t){var e=Math.min(Math.max(t,this.minZoom),this.maxZoom);this._zoom!==e&&(this._unmodified=!1,this._zoom=e,this.scale=this.zoomScale(e),this.tileZoom=Math.floor(e),this.zoomFraction=e-this.tileZoom,this._constrain(),this._calcMatrices());},To.center.get=function(){return this._center},To.center.set=function(t){t.lat===this._center.lat&&t.lng===this._center.lng||(this._unmodified=!1,this._center=t,this._constrain(),this._calcMatrices());},To.padding.get=function(){return this._edgeInsets.toJSON()},To.padding.set=function(t){this._edgeInsets.equals(t)||(this._unmodified=!1,this._edgeInsets.interpolate(this._edgeInsets,t,1),this._calcMatrices());},To.centerPoint.get=function(){return this._edgeInsets.getCenter(this.width,this.height)},wo.prototype.isPaddingEqual=function(t){return this._edgeInsets.equals(t)},wo.prototype.interpolatePadding=function(t,e,i){this._unmodified=!1,this._edgeInsets.interpolate(t,e,i),this._constrain(),this._calcMatrices();},wo.prototype.coveringZoomLevel=function(t){var e=(t.roundZoom?Math.round:Math.floor)(this.zoom+this.scaleZoom(this.tileSize/t.tileSize));return Math.max(0,e)},wo.prototype.getVisibleUnwrappedCoordinates=function(e){var i=[new t.UnwrappedTileID(0,e)];if(this._renderWorldCopies)for(var o=this.pointCoordinate(new t.Point(0,0)),r=this.pointCoordinate(new t.Point(this.width,0)),a=this.pointCoordinate(new t.Point(this.width,this.height)),n=this.pointCoordinate(new t.Point(0,this.height)),s=Math.floor(Math.min(o.x,r.x,a.x,n.x)),l=Math.floor(Math.max(o.x,r.x,a.x,n.x)),c=s-1;c<=l+1;c++)0!==c&&i.push(new t.UnwrappedTileID(c,e));return i},wo.prototype.coveringTiles=function(e){var i=this.coveringZoomLevel(e),o=i;if(void 0!==e.minzoom&&ie.maxzoom&&(i=e.maxzoom);var r=t.MercatorCoordinate.fromLngLat(this.center),a=Math.pow(2,i),n=[a*r.x,a*r.y,0],s=yo.fromInvProjectionMatrix(this.invProjMatrix,this.worldSize,i),l=e.minzoom||0;this.pitch<=60&&this._edgeInsets.top<.1&&(l=i);var c=function(t){return {aabb:new xo([t*a,0,0],[(t+1)*a,a,0]),zoom:0,x:0,y:0,wrap:t,fullyVisible:!1}},u=[],h=[],p=i,d=e.reparseOverscaled?o:i;if(this._renderWorldCopies)for(var _=1;_<=3;_++)u.push(c(-_)),u.push(c(_));for(u.push(c(0));u.length>0;){var f=u.pop(),m=f.x,g=f.y,v=f.fullyVisible;if(!v){var y=f.aabb.intersects(s);if(0===y)continue;v=2===y;}var x=f.aabb.distanceX(n),b=f.aabb.distanceY(n),w=Math.max(Math.abs(x),Math.abs(b));if(f.zoom===p||w>3+(1<=l)h.push({tileID:new t.OverscaledTileID(f.zoom===p?d:f.zoom,f.wrap,f.zoom,m,g),distanceSq:t.sqrLen([n[0]-.5-m,n[1]-.5-g])});else for(var T=0;T<4;T++){var E=(m<<1)+T%2,I=(g<<1)+(T>>1);u.push({aabb:f.aabb.quadrant(T),zoom:f.zoom+1,x:E,y:I,wrap:f.wrap,fullyVisible:v});}}return h.sort((function(t,e){return t.distanceSq-e.distanceSq})).map((function(t){return t.tileID}))},wo.prototype.resize=function(t,e){this.width=t,this.height=e,this.pixelsToGLUnits=[2/t,-2/e],this._constrain(),this._calcMatrices();},To.unmodified.get=function(){return this._unmodified},wo.prototype.zoomScale=function(t){return Math.pow(2,t)},wo.prototype.scaleZoom=function(t){return Math.log(t)/Math.LN2},wo.prototype.project=function(e){var i=t.clamp(e.lat,-this.maxValidLatitude,this.maxValidLatitude);return new t.Point(t.mercatorXfromLng(e.lng)*this.worldSize,t.mercatorYfromLat(i)*this.worldSize)},wo.prototype.unproject=function(e){return new t.MercatorCoordinate(e.x/this.worldSize,e.y/this.worldSize).toLngLat()},To.point.get=function(){return this.project(this.center)},wo.prototype.setLocationAtPoint=function(e,i){var o=this.pointCoordinate(i),r=this.pointCoordinate(this.centerPoint),a=this.locationCoordinate(e),n=new t.MercatorCoordinate(a.x-(o.x-r.x),a.y-(o.y-r.y));this.center=this.coordinateLocation(n),this._renderWorldCopies&&(this.center=this.center.wrap());},wo.prototype.locationPoint=function(t){return this.coordinatePoint(this.locationCoordinate(t))},wo.prototype.pointLocation=function(t){return this.coordinateLocation(this.pointCoordinate(t))},wo.prototype.locationCoordinate=function(e){return t.MercatorCoordinate.fromLngLat(e)},wo.prototype.coordinateLocation=function(t){return t.toLngLat()},wo.prototype.pointCoordinate=function(e){var i=[e.x,e.y,0,1],o=[e.x,e.y,1,1];t.transformMat4(i,i,this.pixelMatrixInverse),t.transformMat4(o,o,this.pixelMatrixInverse);var r=i[3],a=o[3],n=i[1]/r,s=o[1]/a,l=i[2]/r,c=o[2]/a,u=l===c?0:(0-l)/(c-l);return new t.MercatorCoordinate(t.number(i[0]/r,o[0]/a,u)/this.worldSize,t.number(n,s,u)/this.worldSize)},wo.prototype.coordinatePoint=function(e){var i=[e.x*this.worldSize,e.y*this.worldSize,0,1];return t.transformMat4(i,i,this.pixelMatrix),new t.Point(i[0]/i[3],i[1]/i[3])},wo.prototype.getBounds=function(){return (new t.LngLatBounds).extend(this.pointLocation(new t.Point(0,0))).extend(this.pointLocation(new t.Point(this.width,0))).extend(this.pointLocation(new t.Point(this.width,this.height))).extend(this.pointLocation(new t.Point(0,this.height)))},wo.prototype.getMaxBounds=function(){return this.latRange&&2===this.latRange.length&&this.lngRange&&2===this.lngRange.length?new t.LngLatBounds([this.lngRange[0],this.latRange[0]],[this.lngRange[1],this.latRange[1]]):null},wo.prototype.setMaxBounds=function(t){t?(this.lngRange=[t.getWest(),t.getEast()],this.latRange=[t.getSouth(),t.getNorth()],this._constrain()):(this.lngRange=null,this.latRange=[-this.maxValidLatitude,this.maxValidLatitude]);},wo.prototype.calculatePosMatrix=function(e,i){void 0===i&&(i=!1);var o=e.key,r=i?this._alignedPosMatrixCache:this._posMatrixCache;if(r[o])return r[o];var a=e.canonical,n=this.worldSize/this.zoomScale(a.z),s=a.x+Math.pow(2,a.z)*e.wrap,l=t.identity(new Float64Array(16));return t.translate(l,l,[s*n,a.y*n,0]),t.scale(l,l,[n/t.EXTENT,n/t.EXTENT,1]),t.multiply(l,i?this.alignedProjMatrix:this.projMatrix,l),r[o]=new Float32Array(l),r[o]},wo.prototype.customLayerMatrix=function(){return this.mercatorMatrix.slice()},wo.prototype._constrain=function(){if(this.center&&this.width&&this.height&&!this._constraining){this._constraining=!0;var e,i,o,r,a=-90,n=90,s=-180,l=180,c=this.size,u=this._unmodified;if(this.latRange){var h=this.latRange;a=t.mercatorYfromLat(h[1])*this.worldSize,e=(n=t.mercatorYfromLat(h[0])*this.worldSize)-an&&(r=n-m);}if(this.lngRange){var g=d.x,v=c.x/2;g-vl&&(o=l-v);}void 0===o&&void 0===r||(this.center=this.unproject(new t.Point(void 0!==o?o:d.x,void 0!==r?r:d.y))),this._unmodified=u,this._constraining=!1;}},wo.prototype._calcMatrices=function(){if(this.height){var e=this.centerOffset;this.cameraToCenterDistance=.5/Math.tan(this._fov/2)*this.height;var i=Math.PI/2+this._pitch,o=this._fov*(.5+e.y/this.height),r=Math.sin(o)*this.cameraToCenterDistance/Math.sin(t.clamp(Math.PI-i-o,.01,Math.PI-.01)),a=this.point,n=a.x,s=a.y,l=1.01*(Math.cos(Math.PI/2-this._pitch)*r+this.cameraToCenterDistance),c=this.height/50,u=new Float64Array(16);t.perspective(u,this._fov,this.width/this.height,c,l),u[8]=2*-e.x/this.width,u[9]=2*e.y/this.height,t.scale(u,u,[1,-1,1]),t.translate(u,u,[0,0,-this.cameraToCenterDistance]),t.rotateX(u,u,this._pitch),t.rotateZ(u,u,this.angle),t.translate(u,u,[-n,-s,0]),this.mercatorMatrix=t.scale([],u,[this.worldSize,this.worldSize,this.worldSize]),t.scale(u,u,[1,1,t.mercatorZfromAltitude(1,this.center.lat)*this.worldSize,1]),this.projMatrix=u,this.invProjMatrix=t.invert([],this.projMatrix);var h=this.width%2/2,p=this.height%2/2,d=Math.cos(this.angle),_=Math.sin(this.angle),f=n-Math.round(n)+d*h+_*p,m=s-Math.round(s)+d*p+_*h,g=new Float64Array(u);if(t.translate(g,g,[f>.5?f-1:f,m>.5?m-1:m,0]),this.alignedProjMatrix=g,u=t.create(),t.scale(u,u,[this.width/2,-this.height/2,1]),t.translate(u,u,[1,-1,0]),this.labelPlaneMatrix=u,u=t.create(),t.scale(u,u,[1,-1,1]),t.translate(u,u,[-1,-1,0]),t.scale(u,u,[2/this.width,2/this.height,1]),this.glCoordMatrix=u,this.pixelMatrix=t.multiply(new Float64Array(16),this.labelPlaneMatrix,this.projMatrix),!(u=t.invert(new Float64Array(16),this.pixelMatrix)))throw new Error("failed to invert matrix");this.pixelMatrixInverse=u,this._posMatrixCache={},this._alignedPosMatrixCache={};}},wo.prototype.maxPitchScaleFactor=function(){if(!this.pixelMatrixInverse)return 1;var e=this.pointCoordinate(new t.Point(0,0)),i=[e.x*this.worldSize,e.y*this.worldSize,0,1];return t.transformMat4(i,i,this.pixelMatrix)[3]/this.cameraToCenterDistance},wo.prototype.getCameraPoint=function(){var e=Math.tan(this._pitch)*(this.cameraToCenterDistance||1);return this.centerPoint.add(new t.Point(0,e))},wo.prototype.getCameraQueryGeometry=function(e){var i=this.getCameraPoint();if(1===e.length)return [e[0],i];for(var o=i.x,r=i.y,a=i.x,n=i.y,s=0,l=e;s=3&&!t.some((function(t){return isNaN(t)}))){var e=this._map.dragRotate.isEnabled()&&this._map.touchZoomRotate.isEnabled()?+(t[3]||0):this._map.getBearing();return this._map.jumpTo({center:[+t[2],+t[1]],zoom:+t[0],bearing:e,pitch:+(t[4]||0)}),!0}return !1},Eo.prototype._updateHashUnthrottled=function(){var e=this.getHashString();try{t.window.history.replaceState(t.window.history.state,"",e);}catch(t){}};var Io={linearity:.3,easing:t.bezier(0,0,.3,1)},Po=t.extend({deceleration:2500,maxSpeed:1400},Io),So=t.extend({deceleration:20,maxSpeed:1400},Io),Co=t.extend({deceleration:1e3,maxSpeed:360},Io),zo=t.extend({deceleration:1e3,maxSpeed:90},Io),Do=function(t){this._map=t,this.clear();};function Mo(t,e){(!t.duration||t.duration0&&i-e[0].time>160;)e.shift();},Do.prototype._onMoveEnd=function(e){if(this._drainInertiaBuffer(),!(this._inertiaBuffer.length<2)){for(var i={zoom:0,bearing:0,pitch:0,pan:new t.Point(0,0),pinchAround:void 0,around:void 0},o=0,r=this._inertiaBuffer;o=this._clickTolerance||this._map.fire(new Ao(t.type,this._map,t));},Bo.prototype.dblclick=function(t){return this._firePreventable(new Ao(t.type,this._map,t))},Bo.prototype.mouseover=function(t){this._map.fire(new Ao(t.type,this._map,t));},Bo.prototype.mouseout=function(t){this._map.fire(new Ao(t.type,this._map,t));},Bo.prototype.touchstart=function(t){return this._firePreventable(new Ro(t.type,this._map,t))},Bo.prototype.touchmove=function(t){this._map.fire(new Ro(t.type,this._map,t));},Bo.prototype.touchend=function(t){this._map.fire(new Ro(t.type,this._map,t));},Bo.prototype.touchcancel=function(t){this._map.fire(new Ro(t.type,this._map,t));},Bo.prototype._firePreventable=function(t){if(this._map.fire(t),t.defaultPrevented)return {}},Bo.prototype.isEnabled=function(){return !0},Bo.prototype.isActive=function(){return !1},Bo.prototype.enable=function(){},Bo.prototype.disable=function(){};var Oo=function(t){this._map=t;};Oo.prototype.reset=function(){this._delayContextMenu=!1,delete this._contextMenuEvent;},Oo.prototype.mousemove=function(t){this._map.fire(new Ao(t.type,this._map,t));},Oo.prototype.mousedown=function(){this._delayContextMenu=!0;},Oo.prototype.mouseup=function(){this._delayContextMenu=!1,this._contextMenuEvent&&(this._map.fire(new Ao("contextmenu",this._map,this._contextMenuEvent)),delete this._contextMenuEvent);},Oo.prototype.contextmenu=function(t){this._delayContextMenu?this._contextMenuEvent=t:this._map.fire(new Ao(t.type,this._map,t)),this._map.listens("contextmenu")&&t.preventDefault();},Oo.prototype.isEnabled=function(){return !0},Oo.prototype.isActive=function(){return !1},Oo.prototype.enable=function(){},Oo.prototype.disable=function(){};var Fo=function(t,e){this._map=t,this._el=t.getCanvasContainer(),this._container=t.getContainer(),this._clickTolerance=e.clickTolerance||1;};function Uo(t,e){for(var i={},o=0;othis.numTouches)&&(this.aborted=!0),this.aborted||(void 0===this.startTime&&(this.startTime=e.timeStamp),o.length===this.numTouches&&(this.centroid=function(e){for(var i=new t.Point(0,0),o=0,r=e;o30)&&(this.aborted=!0);}}},No.prototype.touchend=function(t,e,i){if((!this.centroid||t.timeStamp-this.startTime>500)&&(this.aborted=!0),0===i.length){var o=!this.aborted&&this.centroid;if(this.reset(),o)return o}};var Zo=function(t){this.singleTap=new No(t),this.numTaps=t.numTaps,this.reset();};Zo.prototype.reset=function(){this.lastTime=1/0,delete this.lastTap,this.count=0,this.singleTap.reset();},Zo.prototype.touchstart=function(t,e,i){this.singleTap.touchstart(t,e,i);},Zo.prototype.touchmove=function(t,e,i){this.singleTap.touchmove(t,e,i);},Zo.prototype.touchend=function(t,e,i){var o=this.singleTap.touchend(t,e,i);if(o){var r=t.timeStamp-this.lastTime<500,a=!this.lastTap||this.lastTap.dist(o)<30;if(r&&a||this.reset(),this.count++,this.lastTime=t.timeStamp,this.lastTap=o,this.count===this.numTaps)return this.reset(),o}};var jo=function(){this._zoomIn=new Zo({numTouches:1,numTaps:2}),this._zoomOut=new Zo({numTouches:2,numTaps:1}),this.reset();};jo.prototype.reset=function(){this._active=!1,this._zoomIn.reset(),this._zoomOut.reset();},jo.prototype.touchstart=function(t,e,i){this._zoomIn.touchstart(t,e,i),this._zoomOut.touchstart(t,e,i);},jo.prototype.touchmove=function(t,e,i){this._zoomIn.touchmove(t,e,i),this._zoomOut.touchmove(t,e,i);},jo.prototype.touchend=function(t,e,i){var o=this,r=this._zoomIn.touchend(t,e,i),a=this._zoomOut.touchend(t,e,i);return r?(this._active=!0,t.preventDefault(),setTimeout((function(){return o.reset()}),0),{cameraAnimation:function(e){return e.easeTo({duration:300,zoom:e.getZoom()+1,around:e.unproject(r)},{originalEvent:t})}}):a?(this._active=!0,t.preventDefault(),setTimeout((function(){return o.reset()}),0),{cameraAnimation:function(e){return e.easeTo({duration:300,zoom:e.getZoom()-1,around:e.unproject(a)},{originalEvent:t})}}):void 0},jo.prototype.touchcancel=function(){this.reset();},jo.prototype.enable=function(){this._enabled=!0;},jo.prototype.disable=function(){this._enabled=!1,this.reset();},jo.prototype.isEnabled=function(){return this._enabled},jo.prototype.isActive=function(){return this._active};var qo=function(t){this.reset(),this._clickTolerance=t.clickTolerance||1;};qo.prototype.reset=function(){this._active=!1,this._moved=!1,delete this._lastPoint,delete this._eventButton;},qo.prototype._correctButton=function(t,e){return !1},qo.prototype._move=function(t,e){return {}},qo.prototype.mousedown=function(t,e){if(!this._lastPoint){var o=i.mouseButton(t);this._correctButton(t,o)&&(this._lastPoint=e,this._eventButton=o);}},qo.prototype.mousemoveWindow=function(t,e){var i=this._lastPoint;if(i&&(t.preventDefault(),this._moved||!(e.dist(i)0&&(this._active=!0);var r=Uo(o,i),a=new t.Point(0,0),n=new t.Point(0,0),s=0;for(var l in r){var c=r[l],u=this._touches[l];u&&(a._add(c),n._add(c.sub(u)),s++,r[l]=c);}if(this._touches=r,!(sMath.abs(t.x)}var er=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e.prototype.reset=function(){t.prototype.reset.call(this),this._valid=void 0,delete this._firstMove,delete this._lastPoints;},e.prototype._start=function(t){this._lastPoints=t,tr(t[0].sub(t[1]))&&(this._valid=!1);},e.prototype._move=function(t,e,i){var o=t[0].sub(this._lastPoints[0]),r=t[1].sub(this._lastPoints[1]);if(this._valid=this.gestureBeginsVertically(o,r,i.timeStamp),this._valid)return this._lastPoints=t,this._active=!0,{pitchDelta:(o.y+r.y)/2*-.5}},e.prototype.gestureBeginsVertically=function(t,e,i){if(void 0!==this._valid)return this._valid;var o=t.mag()>=2,r=e.mag()>=2;if(o||r){if(!o||!r)return void 0===this._firstMove&&(this._firstMove=i),i-this._firstMove<100&&void 0;var a=t.y>0==e.y>0;return tr(t)&&tr(e)&&a}},e}(Ho),ir={panStep:100,bearingStep:15,pitchStep:10},or=function(){var t=ir;this._panStep=t.panStep,this._bearingStep=t.bearingStep,this._pitchStep=t.pitchStep;};function rr(t){return t*(2-t)}or.prototype.reset=function(){this._active=!1;},or.prototype.keydown=function(t){var e=this;if(!(t.altKey||t.ctrlKey||t.metaKey)){var i=0,o=0,r=0,a=0,n=0;switch(t.keyCode){case 61:case 107:case 171:case 187:i=1;break;case 189:case 109:case 173:i=-1;break;case 37:t.shiftKey?o=-1:(t.preventDefault(),a=-1);break;case 39:t.shiftKey?o=1:(t.preventDefault(),a=1);break;case 38:t.shiftKey?r=1:(t.preventDefault(),n=-1);break;case 40:t.shiftKey?r=-1:(t.preventDefault(),n=1);break;default:return}return {cameraAnimation:function(s){var l=s.getZoom();s.easeTo({duration:300,easeId:"keyboardHandler",easing:rr,zoom:i?Math.round(l)+i*(t.shiftKey?2:1):l,bearing:s.getBearing()+o*e._bearingStep,pitch:s.getPitch()+r*e._pitchStep,offset:[-a*e._panStep,-n*e._panStep],center:s.getCenter()},{originalEvent:t});}}}},or.prototype.enable=function(){this._enabled=!0;},or.prototype.disable=function(){this._enabled=!1,this.reset();},or.prototype.isEnabled=function(){return this._enabled},or.prototype.isActive=function(){return this._active};var ar=function(e,i){this._map=e,this._el=e.getCanvasContainer(),this._handler=i,this._delta=0,this._defaultZoomRate=.01,this._wheelZoomRate=1/450,t.bindAll(["_onWheel","_onTimeout","_onScrollFrame","_onScrollFinished"],this);};ar.prototype.setZoomRate=function(t){this._defaultZoomRate=t;},ar.prototype.setWheelZoomRate=function(t){this._wheelZoomRate=t;},ar.prototype.isEnabled=function(){return !!this._enabled},ar.prototype.isActive=function(){return !!this._active||void 0!==this._finishTimeout},ar.prototype.isZooming=function(){return !!this._zooming},ar.prototype.enable=function(t){this.isEnabled()||(this._enabled=!0,this._aroundCenter=t&&"center"===t.around);},ar.prototype.disable=function(){this.isEnabled()&&(this._enabled=!1);},ar.prototype.wheel=function(e){if(this.isEnabled()){var i=e.deltaMode===t.window.WheelEvent.DOM_DELTA_LINE?40*e.deltaY:e.deltaY,o=t.browser.now(),r=o-(this._lastWheelEventTime||0);this._lastWheelEventTime=o,0!==i&&i%4.000244140625==0?this._type="wheel":0!==i&&Math.abs(i)<4?this._type="trackpad":r>400?(this._type=null,this._lastValue=i,this._timeout=setTimeout(this._onTimeout,40,e)):this._type||(this._type=Math.abs(r*i)<200?"trackpad":"wheel",this._timeout&&(clearTimeout(this._timeout),this._timeout=null,i+=this._lastValue)),e.shiftKey&&i&&(i/=4),this._type&&(this._lastWheelEvent=e,this._delta-=i,this._active||this._start(e)),e.preventDefault();}},ar.prototype._onTimeout=function(t){this._type="wheel",this._delta-=this._lastValue,this._active||this._start(t);},ar.prototype._start=function(e){if(this._delta){this._frameId&&(this._frameId=null),this._active=!0,this.isZooming()||(this._zooming=!0),this._finishTimeout&&(clearTimeout(this._finishTimeout),delete this._finishTimeout);var o=i.mousePos(this._el,e);this._around=t.LngLat.convert(this._aroundCenter?this._map.getCenter():this._map.unproject(o)),this._aroundPoint=this._map.transform.locationPoint(this._around),this._frameId||(this._frameId=!0,this._handler._triggerRenderFrame());}},ar.prototype.renderFrame=function(){return this._onScrollFrame()},ar.prototype._onScrollFrame=function(){var e=this;if(this._frameId&&(this._frameId=null,this.isActive())){var i=this._map.transform;if(0!==this._delta){var o="wheel"===this._type&&Math.abs(this._delta)>4.000244140625?this._wheelZoomRate:this._defaultZoomRate,r=2/(1+Math.exp(-Math.abs(this._delta*o)));this._delta<0&&0!==r&&(r=1/r);var a="number"==typeof this._targetZoom?i.zoomScale(this._targetZoom):i.scale;this._targetZoom=Math.min(i.maxZoom,Math.max(i.minZoom,i.scaleZoom(a*r))),"wheel"===this._type&&(this._startZoom=i.zoom,this._easing=this._smoothOutEasing(200)),this._delta=0;}var n,s="number"==typeof this._targetZoom?this._targetZoom:i.zoom,l=this._startZoom,c=this._easing,u=!1;if("wheel"===this._type&&l&&c){var h=Math.min((t.browser.now()-this._lastWheelEventTime)/200,1),p=c(h);n=t.number(l,s,p),h<1?this._frameId||(this._frameId=!0):u=!0;}else n=s,u=!0;return this._active=!0,u&&(this._active=!1,this._finishTimeout=setTimeout((function(){e._zooming=!1,e._handler._triggerRenderFrame(),delete e._targetZoom,delete e._finishTimeout;}),200)),{noInertia:!0,needsRenderFrame:!u,zoomDelta:n-i.zoom,around:this._aroundPoint,originalEvent:this._lastWheelEvent}}},ar.prototype._smoothOutEasing=function(e){var i=t.ease;if(this._prevEase){var o=this._prevEase,r=(t.browser.now()-o.start)/o.duration,a=o.easing(r+.01)-o.easing(r),n=.27/Math.sqrt(a*a+1e-4)*.01,s=Math.sqrt(.0729-n*n);i=t.bezier(n,s,.25,1);}return this._prevEase={start:t.browser.now(),duration:e,easing:i},i},ar.prototype.reset=function(){this._active=!1;};var nr=function(t,e){this._clickZoom=t,this._tapZoom=e;};nr.prototype.enable=function(){this._clickZoom.enable(),this._tapZoom.enable();},nr.prototype.disable=function(){this._clickZoom.disable(),this._tapZoom.disable();},nr.prototype.isEnabled=function(){return this._clickZoom.isEnabled()&&this._tapZoom.isEnabled()},nr.prototype.isActive=function(){return this._clickZoom.isActive()||this._tapZoom.isActive()};var sr=function(){this.reset();};sr.prototype.reset=function(){this._active=!1;},sr.prototype.dblclick=function(t,e){return t.preventDefault(),{cameraAnimation:function(i){i.easeTo({duration:300,zoom:i.getZoom()+(t.shiftKey?-1:1),around:i.unproject(e)},{originalEvent:t});}}},sr.prototype.enable=function(){this._enabled=!0;},sr.prototype.disable=function(){this._enabled=!1,this.reset();},sr.prototype.isEnabled=function(){return this._enabled},sr.prototype.isActive=function(){return this._active};var lr=function(){this._tap=new Zo({numTouches:1,numTaps:1}),this.reset();};lr.prototype.reset=function(){this._active=!1,delete this._swipePoint,delete this._swipeTouch,delete this._tapTime,this._tap.reset();},lr.prototype.touchstart=function(t,e,i){this._swipePoint||(this._tapTime&&t.timeStamp-this._tapTime>500&&this.reset(),this._tapTime?i.length>0&&(this._swipePoint=e[0],this._swipeTouch=i[0].identifier):this._tap.touchstart(t,e,i));},lr.prototype.touchmove=function(t,e,i){if(this._tapTime){if(this._swipePoint){if(i[0].identifier!==this._swipeTouch)return;var o=e[0],r=o.y-this._swipePoint.y;return this._swipePoint=o,t.preventDefault(),this._active=!0,{zoomDelta:r/128}}}else this._tap.touchmove(t,e,i);},lr.prototype.touchend=function(t,e,i){this._tapTime?this._swipePoint&&0===i.length&&this.reset():this._tap.touchend(t,e,i)&&(this._tapTime=t.timeStamp);},lr.prototype.touchcancel=function(){this.reset();},lr.prototype.enable=function(){this._enabled=!0;},lr.prototype.disable=function(){this._enabled=!1,this.reset();},lr.prototype.isEnabled=function(){return this._enabled},lr.prototype.isActive=function(){return this._active};var cr=function(t,e,i){this._el=t,this._mousePan=e,this._touchPan=i;};cr.prototype.enable=function(t){this._inertiaOptions=t||{},this._mousePan.enable(),this._touchPan.enable(),this._el.classList.add("mapboxgl-touch-drag-pan");},cr.prototype.disable=function(){this._mousePan.disable(),this._touchPan.disable(),this._el.classList.remove("mapboxgl-touch-drag-pan");},cr.prototype.isEnabled=function(){return this._mousePan.isEnabled()&&this._touchPan.isEnabled()},cr.prototype.isActive=function(){return this._mousePan.isActive()||this._touchPan.isActive()};var ur=function(t,e,i){this._pitchWithRotate=t.pitchWithRotate,this._mouseRotate=e,this._mousePitch=i;};ur.prototype.enable=function(){this._mouseRotate.enable(),this._pitchWithRotate&&this._mousePitch.enable();},ur.prototype.disable=function(){this._mouseRotate.disable(),this._mousePitch.disable();},ur.prototype.isEnabled=function(){return this._mouseRotate.isEnabled()&&(!this._pitchWithRotate||this._mousePitch.isEnabled())},ur.prototype.isActive=function(){return this._mouseRotate.isActive()||this._mousePitch.isActive()};var hr=function(t,e,i,o){this._el=t,this._touchZoom=e,this._touchRotate=i,this._tapDragZoom=o,this._rotationDisabled=!1,this._enabled=!0;};hr.prototype.enable=function(t){this._touchZoom.enable(t),this._rotationDisabled||this._touchRotate.enable(t),this._tapDragZoom.enable(),this._el.classList.add("mapboxgl-touch-zoom-rotate");},hr.prototype.disable=function(){this._touchZoom.disable(),this._touchRotate.disable(),this._tapDragZoom.disable(),this._el.classList.remove("mapboxgl-touch-zoom-rotate");},hr.prototype.isEnabled=function(){return this._touchZoom.isEnabled()&&(this._rotationDisabled||this._touchRotate.isEnabled())&&this._tapDragZoom.isEnabled()},hr.prototype.isActive=function(){return this._touchZoom.isActive()||this._touchRotate.isActive()||this._tapDragZoom.isActive()},hr.prototype.disableRotation=function(){this._rotationDisabled=!0,this._touchRotate.disable();},hr.prototype.enableRotation=function(){this._rotationDisabled=!1,this._touchZoom.isEnabled()&&this._touchRotate.enable();};var pr=function(t){return t.zoom||t.drag||t.pitch||t.rotate},dr=function(t){function e(){t.apply(this,arguments);}return t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e,e}(t.Event);function _r(t){return t.panDelta&&t.panDelta.mag()||t.zoomDelta||t.bearingDelta||t.pitchDelta}var fr=function(e,o){this._map=e,this._el=this._map.getCanvasContainer(),this._handlers=[],this._handlersById={},this._changes=[],this._inertia=new Do(e),this._bearingSnap=o.bearingSnap,this._previousActiveHandlers={},this._eventsInProgress={},this._addDefaultHandlers(o),t.bindAll(["handleEvent","handleWindowEvent"],this);var r=this._el;this._listeners=[[r,"touchstart",{passive:!1}],[r,"touchmove",{passive:!1}],[r,"touchend",void 0],[r,"touchcancel",void 0],[r,"mousedown",void 0],[r,"mousemove",void 0],[r,"mouseup",void 0],[t.window.document,"mousemove",{capture:!0}],[t.window.document,"mouseup",void 0],[r,"mouseover",void 0],[r,"mouseout",void 0],[r,"dblclick",void 0],[r,"click",void 0],[r,"keydown",{capture:!1}],[r,"keyup",void 0],[r,"wheel",{passive:!1}],[r,"contextmenu",void 0],[t.window,"blur",void 0]];for(var a=0,n=this._listeners;aa?Math.min(2,b):Math.max(.5,b),w=Math.pow(m,1-e),T=r.unproject(y.add(x.mult(e*w)).mult(f));r.setLocationAtPoint(r.renderWorldCopies?T.wrap():T,_);}o._fireMoveEvents(i);}),(function(t){o._afterEase(i,t);}),e),this},i.prototype._prepareEase=function(e,i,o){void 0===o&&(o={}),this._moving=!0,i||o.moving||this.fire(new t.Event("movestart",e)),this._zooming&&!o.zooming&&this.fire(new t.Event("zoomstart",e)),this._rotating&&!o.rotating&&this.fire(new t.Event("rotatestart",e)),this._pitching&&!o.pitching&&this.fire(new t.Event("pitchstart",e));},i.prototype._fireMoveEvents=function(e){this.fire(new t.Event("move",e)),this._zooming&&this.fire(new t.Event("zoom",e)),this._rotating&&this.fire(new t.Event("rotate",e)),this._pitching&&this.fire(new t.Event("pitch",e));},i.prototype._afterEase=function(e,i){if(!this._easeId||!i||this._easeId!==i){delete this._easeId;var o=this._zooming,r=this._rotating,a=this._pitching;this._moving=!1,this._zooming=!1,this._rotating=!1,this._pitching=!1,this._padding=!1,o&&this.fire(new t.Event("zoomend",e)),r&&this.fire(new t.Event("rotateend",e)),a&&this.fire(new t.Event("pitchend",e)),this.fire(new t.Event("moveend",e));}},i.prototype.flyTo=function(e,i){var o=this;if(!e.essential&&t.browser.prefersReducedMotion){var r=t.pick(e,["center","zoom","bearing","pitch","around"]);return this.jumpTo(r,i)}this.stop(),e=t.extend({offset:[0,0],speed:1.2,curve:1.42,easing:t.ease},e);var a=this.transform,n=this.getZoom(),s=this.getBearing(),l=this.getPitch(),c=this.getPadding(),u="zoom"in e?t.clamp(+e.zoom,a.minZoom,a.maxZoom):n,h="bearing"in e?this._normalizeBearing(e.bearing,s):s,p="pitch"in e?+e.pitch:l,d="padding"in e?e.padding:a.padding,_=a.zoomScale(u-n),f=t.Point.convert(e.offset),m=a.centerPoint.add(f),g=a.pointLocation(m),v=t.LngLat.convert(e.center||g);this._normalizeCenter(v);var y=a.project(g),x=a.project(v).sub(y),b=e.curve,w=Math.max(a.width,a.height),T=w/_,E=x.mag();if("minZoom"in e){var I=t.clamp(Math.min(e.minZoom,n,u),a.minZoom,a.maxZoom),P=w/a.zoomScale(I-n);b=Math.sqrt(P/E*2);}var S=b*b;function C(t){var e=(T*T-w*w+(t?-1:1)*S*S*E*E)/(2*(t?T:w)*S*E);return Math.log(Math.sqrt(e*e+1)-e)}function z(t){return (Math.exp(t)-Math.exp(-t))/2}function D(t){return (Math.exp(t)+Math.exp(-t))/2}var M=C(0),L=function(t){return D(M)/D(M+b*t)},A=function(t){return w*((D(M)*(z(e=M+b*t)/D(e))-z(M))/S)/E;var e;},R=(C(1)-M)/b;if(Math.abs(E)<1e-6||!isFinite(R)){if(Math.abs(w-T)<1e-6)return this.easeTo(e,i);var k=Te.maxDuration&&(e.duration=0),this._zooming=!0,this._rotating=s!==h,this._pitching=p!==l,this._padding=!a.isPaddingEqual(d),this._prepareEase(i,!1),this._ease((function(e){var r=e*R,_=1/L(r);a.zoom=1===e?u:n+a.scaleZoom(_),o._rotating&&(a.bearing=t.number(s,h,e)),o._pitching&&(a.pitch=t.number(l,p,e)),o._padding&&(a.interpolatePadding(c,d,e),m=a.centerPoint.add(f));var g=1===e?v:a.unproject(y.add(x.mult(A(r))).mult(_));a.setLocationAtPoint(a.renderWorldCopies?g.wrap():g,m),o._fireMoveEvents(i);}),(function(){return o._afterEase(i)}),e),this},i.prototype.isEasing=function(){return !!this._easeFrameId},i.prototype.stop=function(){return this._stop()},i.prototype._stop=function(t,e){if(this._easeFrameId&&(this._cancelRenderFrame(this._easeFrameId),delete this._easeFrameId,delete this._onEaseFrame),this._onEaseEnd){var i=this._onEaseEnd;delete this._onEaseEnd,i.call(this,e);}if(!t){var o=this.handlers;o&&o.stop();}return this},i.prototype._ease=function(e,i,o){!1===o.animate||0===o.duration?(e(1),i()):(this._easeStart=t.browser.now(),this._easeOptions=o,this._onEaseFrame=e,this._onEaseEnd=i,this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback));},i.prototype._renderFrameCallback=function(){var e=Math.min((t.browser.now()-this._easeStart)/this._easeOptions.duration,1);this._onEaseFrame(this._easeOptions.easing(e)),e<1?this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback):this.stop();},i.prototype._normalizeBearing=function(e,i){e=t.wrap(e,-180,180);var o=Math.abs(e-i);return Math.abs(e-360-i)180?-360:i<-180?360:0;}},i}(t.Evented),gr=function(e){void 0===e&&(e={}),this.options=e,t.bindAll(["_updateEditLink","_updateData","_updateCompact"],this);};gr.prototype.getDefaultPosition=function(){return "bottom-right"},gr.prototype.onAdd=function(t){var e=this.options&&this.options.compact;return this._map=t,this._container=i.create("div","mapboxgl-ctrl mapboxgl-ctrl-attrib"),this._innerContainer=i.create("div","mapboxgl-ctrl-attrib-inner",this._container),e&&this._container.classList.add("mapboxgl-compact"),this._updateAttributions(),this._updateEditLink(),this._map.on("styledata",this._updateData),this._map.on("sourcedata",this._updateData),this._map.on("moveend",this._updateEditLink),void 0===e&&(this._map.on("resize",this._updateCompact),this._updateCompact()),this._container},gr.prototype.onRemove=function(){i.remove(this._container),this._map.off("styledata",this._updateData),this._map.off("sourcedata",this._updateData),this._map.off("moveend",this._updateEditLink),this._map.off("resize",this._updateCompact),this._map=void 0,this._attribHTML=void 0;},gr.prototype._updateEditLink=function(){var e=this._editLink;e||(e=this._editLink=this._container.querySelector(".mapbox-improve-map"));var i=[{key:"owner",value:this.styleOwner},{key:"id",value:this.styleId},{key:"access_token",value:this._map._requestManager._customAccessToken||t.config.ACCESS_TOKEN}];if(e){var o=i.reduce((function(t,e,o){return e.value&&(t+=e.key+"="+e.value+(o=0)return !1;return !0}))).join(" | ");n!==this._attribHTML&&(this._attribHTML=n,t.length?(this._innerContainer.innerHTML=n,this._container.classList.remove("mapboxgl-attrib-empty")):this._container.classList.add("mapboxgl-attrib-empty"),this._editLink=null);}},gr.prototype._updateCompact=function(){this._map.getCanvasContainer().offsetWidth<=640?this._container.classList.add("mapboxgl-compact"):this._container.classList.remove("mapboxgl-compact");};var vr=function(){t.bindAll(["_updateLogo"],this),t.bindAll(["_updateCompact"],this);};vr.prototype.onAdd=function(t){this._map=t,this._container=i.create("div","mapboxgl-ctrl");var e=i.create("a","mapboxgl-ctrl-logo");return e.target="_blank",e.rel="noopener nofollow",e.href="https://www.mapbox.com/",e.setAttribute("aria-label",this._map._getUIString("LogoControl.Title")),e.setAttribute("rel","noopener nofollow"),this._container.appendChild(e),this._container.style.display="none",this._map.on("sourcedata",this._updateLogo),this._updateLogo(),this._map.on("resize",this._updateCompact),this._updateCompact(),this._container},vr.prototype.onRemove=function(){i.remove(this._container),this._map.off("sourcedata",this._updateLogo),this._map.off("resize",this._updateCompact);},vr.prototype.getDefaultPosition=function(){return "bottom-left"},vr.prototype._updateLogo=function(t){t&&"metadata"!==t.sourceDataType||(this._container.style.display=this._logoRequired()?"block":"none");},vr.prototype._logoRequired=function(){if(this._map.style){var t=this._map.style.sourceCaches;for(var e in t)if(t[e].getSource().mapbox_logo)return !0;return !1}},vr.prototype._updateCompact=function(){var t=this._container.children;if(t.length){var e=t[0];this._map.getCanvasContainer().offsetWidth<250?e.classList.add("mapboxgl-compact"):e.classList.remove("mapboxgl-compact");}};var yr=function(){this._queue=[],this._id=0,this._cleared=!1,this._currentlyRunning=!1;};yr.prototype.add=function(t){var e=++this._id;return this._queue.push({callback:t,id:e,cancelled:!1}),e},yr.prototype.remove=function(t){for(var e=this._currentlyRunning,i=0,o=e?this._queue.concat(e):this._queue;ie.maxZoom)throw new Error("maxZoom must be greater than or equal to minZoom");if(null!=e.minPitch&&null!=e.maxPitch&&e.minPitch>e.maxPitch)throw new Error("maxPitch must be greater than or equal to minPitch");if(null!=e.minPitch&&e.minPitch<0)throw new Error("minPitch must be greater than or equal to 0");if(null!=e.maxPitch&&e.maxPitch>60)throw new Error("maxPitch must be less than or equal to 60");var r=new wo(e.minZoom,e.maxZoom,e.minPitch,e.maxPitch,e.renderWorldCopies);if(o.call(this,r,e),this._interactive=e.interactive,this._maxTileCacheSize=e.maxTileCacheSize,this._failIfMajorPerformanceCaveat=e.failIfMajorPerformanceCaveat,this._preserveDrawingBuffer=e.preserveDrawingBuffer,this._antialias=e.antialias,this._trackResize=e.trackResize,this._bearingSnap=e.bearingSnap,this._refreshExpiredTiles=e.refreshExpiredTiles,this._fadeDuration=e.fadeDuration,this._crossSourceCollisions=e.crossSourceCollisions,this._crossFadingFactor=1,this._collectResourceTiming=e.collectResourceTiming,this._renderTaskQueue=new yr,this._controls=[],this._mapId=t.uniqueId(),this._locale=t.extend({},xr,e.locale),this._requestManager=new t.RequestManager(e.transformRequest,e.accessToken),"string"==typeof e.container){if(this._container=t.window.document.getElementById(e.container),!this._container)throw new Error("Container '"+e.container+"' not found.")}else {if(!(e.container instanceof wr))throw new Error("Invalid type: 'container' must be a String or HTMLElement.");this._container=e.container;}if(e.maxBounds&&this.setMaxBounds(e.maxBounds),t.bindAll(["_onWindowOnline","_onWindowResize","_contextLost","_contextRestored"],this),this._setupContainer(),this._setupPainter(),void 0===this.painter)throw new Error("Failed to initialize WebGL.");this.on("move",(function(){return i._update(!1)})),this.on("moveend",(function(){return i._update(!1)})),this.on("zoom",(function(){return i._update(!0)})),void 0!==t.window&&(t.window.addEventListener("online",this._onWindowOnline,!1),t.window.addEventListener("resize",this._onWindowResize,!1)),this.handlers=new fr(this,e),this._hash=e.hash&&new Eo("string"==typeof e.hash&&e.hash||void 0).addTo(this),this._hash&&this._hash._onHashChange()||(this.jumpTo({center:e.center,zoom:e.zoom,bearing:e.bearing,pitch:e.pitch}),e.bounds&&(this.resize(),this.fitBounds(e.bounds,t.extend({},e.fitBoundsOptions,{duration:0})))),this.resize(),this._localIdeographFontFamily=e.localIdeographFontFamily,e.style&&this.setStyle(e.style,{localIdeographFontFamily:e.localIdeographFontFamily}),e.attributionControl&&this.addControl(new gr({customAttribution:e.customAttribution})),this.addControl(new vr,e.logoPosition),this.on("style.load",(function(){i.transform.unmodified&&i.jumpTo(i.style.stylesheet);})),this.on("data",(function(e){i._update("style"===e.dataType),i.fire(new t.Event(e.dataType+"data",e));})),this.on("dataloading",(function(e){i.fire(new t.Event(e.dataType+"dataloading",e));}));}o&&(r.__proto__=o),(r.prototype=Object.create(o&&o.prototype)).constructor=r;var a={showTileBoundaries:{configurable:!0},showPadding:{configurable:!0},showCollisionBoxes:{configurable:!0},showOverdrawInspector:{configurable:!0},repaint:{configurable:!0},vertices:{configurable:!0},version:{configurable:!0}};return r.prototype._getMapId=function(){return this._mapId},r.prototype.addControl=function(e,i){if(void 0===i&&e.getDefaultPosition&&(i=e.getDefaultPosition()),void 0===i&&(i="top-right"),!e||!e.onAdd)return this.fire(new t.ErrorEvent(new Error("Invalid argument to map.addControl(). Argument must be a control with onAdd and onRemove methods.")));var o=e.onAdd(this);this._controls.push(e);var r=this._controlPositions[i];return -1!==i.indexOf("bottom")?r.insertBefore(o,r.firstChild):r.appendChild(o),this},r.prototype.removeControl=function(e){if(!e||!e.onRemove)return this.fire(new t.ErrorEvent(new Error("Invalid argument to map.removeControl(). Argument must be a control with onAdd and onRemove methods.")));var i=this._controls.indexOf(e);return i>-1&&this._controls.splice(i,1),e.onRemove(this),this},r.prototype.resize=function(e){var i=this._containerDimensions(),o=i[0],r=i[1];this._resizeCanvas(o,r),this.transform.resize(o,r),this.painter.resize(o,r);var a=!this._moving;return a&&(this.stop(),this.fire(new t.Event("movestart",e)).fire(new t.Event("move",e))),this.fire(new t.Event("resize",e)),a&&this.fire(new t.Event("moveend",e)),this},r.prototype.getBounds=function(){return this.transform.getBounds()},r.prototype.getMaxBounds=function(){return this.transform.getMaxBounds()},r.prototype.setMaxBounds=function(e){return this.transform.setMaxBounds(t.LngLatBounds.convert(e)),this._update()},r.prototype.setMinZoom=function(t){if((t=null==t?-2:t)>=-2&&t<=this.transform.maxZoom)return this.transform.minZoom=t,this._update(),this.getZoom()=this.transform.minZoom)return this.transform.maxZoom=t,this._update(),this.getZoom()>t&&this.setZoom(t),this;throw new Error("maxZoom must be greater than the current minZoom")},r.prototype.getMaxZoom=function(){return this.transform.maxZoom},r.prototype.setMinPitch=function(t){if((t=null==t?0:t)<0)throw new Error("minPitch must be greater than or equal to 0");if(t>=0&&t<=this.transform.maxPitch)return this.transform.minPitch=t,this._update(),this.getPitch()60)throw new Error("maxPitch must be less than or equal to 60");if(t>=this.transform.minPitch)return this.transform.maxPitch=t,this._update(),this.getPitch()>t&&this.setPitch(t),this;throw new Error("maxPitch must be greater than the current minPitch")},r.prototype.getMaxPitch=function(){return this.transform.maxPitch},r.prototype.getRenderWorldCopies=function(){return this.transform.renderWorldCopies},r.prototype.setRenderWorldCopies=function(t){return this.transform.renderWorldCopies=t,this._update()},r.prototype.project=function(e){return this.transform.locationPoint(t.LngLat.convert(e))},r.prototype.unproject=function(e){return this.transform.pointLocation(t.Point.convert(e))},r.prototype.isMoving=function(){return this._moving||this.handlers.isMoving()},r.prototype.isZooming=function(){return this._zooming||this.handlers.isZooming()},r.prototype.isRotating=function(){return this._rotating||this.handlers.isRotating()},r.prototype._createDelegatedListener=function(t,e,i){var o,r=this;if("mouseenter"===t||"mouseover"===t){var a=!1;return {layer:e,listener:i,delegates:{mousemove:function(o){var n=r.getLayer(e)?r.queryRenderedFeatures(o.point,{layers:[e]}):[];n.length?a||(a=!0,i.call(r,new Ao(t,r,o.originalEvent,{features:n}))):a=!1;},mouseout:function(){a=!1;}}}}if("mouseleave"===t||"mouseout"===t){var n=!1;return {layer:e,listener:i,delegates:{mousemove:function(o){(r.getLayer(e)?r.queryRenderedFeatures(o.point,{layers:[e]}):[]).length?n=!0:n&&(n=!1,i.call(r,new Ao(t,r,o.originalEvent)));},mouseout:function(e){n&&(n=!1,i.call(r,new Ao(t,r,e.originalEvent)));}}}}return {layer:e,listener:i,delegates:(o={},o[t]=function(t){var o=r.getLayer(e)?r.queryRenderedFeatures(t.point,{layers:[e]}):[];o.length&&(t.features=o,i.call(r,t),delete t.features);},o)}},r.prototype.on=function(t,e,i){if(void 0===i)return o.prototype.on.call(this,t,e);var r=this._createDelegatedListener(t,e,i);for(var a in this._delegatedListeners=this._delegatedListeners||{},this._delegatedListeners[t]=this._delegatedListeners[t]||[],this._delegatedListeners[t].push(r),r.delegates)this.on(a,r.delegates[a]);return this},r.prototype.once=function(t,e,i){if(void 0===i)return o.prototype.once.call(this,t,e);var r=this._createDelegatedListener(t,e,i);for(var a in r.delegates)this.once(a,r.delegates[a]);return this},r.prototype.off=function(t,e,i){var r=this;return void 0===i?o.prototype.off.call(this,t,e):(this._delegatedListeners&&this._delegatedListeners[t]&&function(o){for(var a=o[t],n=0;n180;){var s=o.locationPoint(e);if(s.x>=0&&s.y>=0&&s.x<=o.width&&s.y<=o.height)break;e.lng>o.center.lng?e.lng-=360:e.lng+=360;}return e}zr.prototype.down=function(t,e){this.mouseRotate.mousedown(t,e),this.mousePitch&&this.mousePitch.mousedown(t,e),i.disableDrag();},zr.prototype.move=function(t,e){var i=this.map,o=this.mouseRotate.mousemoveWindow(t,e);if(o&&o.bearingDelta&&i.setBearing(i.getBearing()+o.bearingDelta),this.mousePitch){var r=this.mousePitch.mousemoveWindow(t,e);r&&r.pitchDelta&&i.setPitch(i.getPitch()+r.pitchDelta);}},zr.prototype.off=function(){var t=this.element;i.removeEventListener(t,"mousedown",this.mousedown),i.removeEventListener(t,"touchstart",this.touchstart,{passive:!1}),i.removeEventListener(t,"touchmove",this.touchmove),i.removeEventListener(t,"touchend",this.touchend),i.removeEventListener(t,"touchcancel",this.reset),this.offTemp();},zr.prototype.offTemp=function(){i.enableDrag(),i.removeEventListener(t.window,"mousemove",this.mousemove),i.removeEventListener(t.window,"mouseup",this.mouseup);},zr.prototype.mousedown=function(e){this.down(t.extend({},e,{ctrlKey:!0,preventDefault:function(){return e.preventDefault()}}),i.mousePos(this.element,e)),i.addEventListener(t.window,"mousemove",this.mousemove),i.addEventListener(t.window,"mouseup",this.mouseup);},zr.prototype.mousemove=function(t){this.move(t,i.mousePos(this.element,t));},zr.prototype.mouseup=function(t){this.mouseRotate.mouseupWindow(t),this.mousePitch&&this.mousePitch.mouseupWindow(t),this.offTemp();},zr.prototype.touchstart=function(t){1!==t.targetTouches.length?this.reset():(this._startPos=this._lastPos=i.touchPos(this.element,t.targetTouches)[0],this.down({type:"mousedown",button:0,ctrlKey:!0,preventDefault:function(){return t.preventDefault()}},this._startPos));},zr.prototype.touchmove=function(t){1!==t.targetTouches.length?this.reset():(this._lastPos=i.touchPos(this.element,t.targetTouches)[0],this.move({preventDefault:function(){return t.preventDefault()}},this._lastPos));},zr.prototype.touchend=function(t){0===t.targetTouches.length&&this._startPos&&this._lastPos&&this._startPos.dist(this._lastPos)e.getEast()||i.latitudee.getNorth())},o.prototype._setErrorState=function(){switch(this._watchState){case"WAITING_ACTIVE":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active-error");break;case"ACTIVE_LOCK":this._watchState="ACTIVE_ERROR",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting");break;case"BACKGROUND":this._watchState="BACKGROUND_ERROR",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting");}},o.prototype._onSuccess=function(e){if(this._map){if(this._isOutOfMapMaxBounds(e))return this._setErrorState(),this.fire(new t.Event("outofmaxbounds",e)),this._updateMarker(),void this._finish();if(this.options.trackUserLocation)switch(this._lastKnownPosition=e,this._watchState){case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active");break;case"BACKGROUND":case"BACKGROUND_ERROR":this._watchState="BACKGROUND",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background-error"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background");}this.options.showUserLocation&&"OFF"!==this._watchState&&this._updateMarker(e),this.options.trackUserLocation&&"ACTIVE_LOCK"!==this._watchState||this._updateCamera(e),this.options.showUserLocation&&this._dotElement.classList.remove("mapboxgl-user-location-dot-stale"),this.fire(new t.Event("geolocate",e)),this._finish();}},o.prototype._updateCamera=function(e){var i=new t.LngLat(e.coords.longitude,e.coords.latitude),o=e.coords.accuracy,r=this._map.getBearing(),a=t.extend({bearing:r},this.options.fitBoundsOptions);this._map.fitBounds(i.toBounds(o),a,{geolocateSource:!0});},o.prototype._updateMarker=function(e){if(e){var i=new t.LngLat(e.coords.longitude,e.coords.latitude);this._accuracyCircleMarker.setLngLat(i).addTo(this._map),this._userLocationDotMarker.setLngLat(i).addTo(this._map),this._accuracy=e.coords.accuracy,this.options.showUserLocation&&this.options.showAccuracyCircle&&this._updateCircleRadius();}else this._userLocationDotMarker.remove(),this._accuracyCircleMarker.remove();},o.prototype._updateCircleRadius=function(){var t=this._map._container.clientHeight/2,e=this._map.unproject([0,t]),i=this._map.unproject([1,t]),o=e.distanceTo(i),r=Math.ceil(2*this._accuracy/o);this._circleElement.style.width=r+"px",this._circleElement.style.height=r+"px";},o.prototype._onZoom=function(){this.options.showUserLocation&&this.options.showAccuracyCircle&&this._updateCircleRadius();},o.prototype._onError=function(e){if(this._map){if(this.options.trackUserLocation)if(1===e.code){this._watchState="OFF",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background-error"),this._geolocateButton.disabled=!0;var i=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.title=i,this._geolocateButton.setAttribute("aria-label",i),void 0!==this._geolocationWatchID&&this._clearWatch();}else {if(3===e.code&&Or)return;this._setErrorState();}"OFF"!==this._watchState&&this.options.showUserLocation&&this._dotElement.classList.add("mapboxgl-user-location-dot-stale"),this.fire(new t.Event("error",e)),this._finish();}},o.prototype._finish=function(){this._timeoutId&&clearTimeout(this._timeoutId),this._timeoutId=void 0;},o.prototype._setupUI=function(e){var o=this;if(this._container.addEventListener("contextmenu",(function(t){return t.preventDefault()})),this._geolocateButton=i.create("button","mapboxgl-ctrl-geolocate",this._container),i.create("span","mapboxgl-ctrl-icon",this._geolocateButton).setAttribute("aria-hidden",!0),this._geolocateButton.type="button",!1===e){t.warnOnce("Geolocation support is not available so the GeolocateControl will be disabled.");var r=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.disabled=!0,this._geolocateButton.title=r,this._geolocateButton.setAttribute("aria-label",r);}else {var a=this._map._getUIString("GeolocateControl.FindMyLocation");this._geolocateButton.title=a,this._geolocateButton.setAttribute("aria-label",a);}this.options.trackUserLocation&&(this._geolocateButton.setAttribute("aria-pressed","false"),this._watchState="OFF"),this.options.showUserLocation&&(this._dotElement=i.create("div","mapboxgl-user-location-dot"),this._userLocationDotMarker=new Rr(this._dotElement),this._circleElement=i.create("div","mapboxgl-user-location-accuracy-circle"),this._accuracyCircleMarker=new Rr({element:this._circleElement,pitchAlignment:"map"}),this.options.trackUserLocation&&(this._watchState="OFF"),this._map.on("zoom",this._onZoom)),this._geolocateButton.addEventListener("click",this.trigger.bind(this)),this._setup=!0,this.options.trackUserLocation&&this._map.on("movestart",(function(e){e.geolocateSource||"ACTIVE_LOCK"!==o._watchState||e.originalEvent&&"resize"===e.originalEvent.type||(o._watchState="BACKGROUND",o._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background"),o._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),o.fire(new t.Event("trackuserlocationend")));}));},o.prototype.trigger=function(){if(!this._setup)return t.warnOnce("Geolocate control triggered before added to a map"),!1;if(this.options.trackUserLocation){switch(this._watchState){case"OFF":this._watchState="WAITING_ACTIVE",this.fire(new t.Event("trackuserlocationstart"));break;case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":case"BACKGROUND_ERROR":Br--,Or=!1,this._watchState="OFF",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-active-error"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background-error"),this.fire(new t.Event("trackuserlocationend"));break;case"BACKGROUND":this._watchState="ACTIVE_LOCK",this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-background"),this._lastKnownPosition&&this._updateCamera(this._lastKnownPosition),this.fire(new t.Event("trackuserlocationstart"));}switch(this._watchState){case"WAITING_ACTIVE":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active");break;case"ACTIVE_LOCK":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active");break;case"ACTIVE_ERROR":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-active-error");break;case"BACKGROUND":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background");break;case"BACKGROUND_ERROR":this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-background-error");}if("OFF"===this._watchState&&void 0!==this._geolocationWatchID)this._clearWatch();else if(void 0===this._geolocationWatchID){var e;this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","true"),++Br>1?(e={maximumAge:6e5,timeout:0},Or=!0):(e=this.options.positionOptions,Or=!1),this._geolocationWatchID=t.window.navigator.geolocation.watchPosition(this._onSuccess,this._onError,e);}}else t.window.navigator.geolocation.getCurrentPosition(this._onSuccess,this._onError,this.options.positionOptions),this._timeoutId=setTimeout(this._finish,1e4);return !0},o.prototype._clearWatch=function(){t.window.navigator.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0,this._geolocateButton.classList.remove("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","false"),this.options.showUserLocation&&this._updateMarker(null);},o}(t.Evented),Ur={maxWidth:100,unit:"metric"},Nr=function(e){this.options=t.extend({},Ur,e),t.bindAll(["_onMove","setUnit"],this);};function Zr(t,e,i){var o=i&&i.maxWidth||100,r=t._container.clientHeight/2,a=t.unproject([0,r]),n=t.unproject([o,r]),s=a.distanceTo(n);if(i&&"imperial"===i.unit){var l=3.2808*s;l>5280?jr(e,o,l/5280,t._getUIString("ScaleControl.Miles")):jr(e,o,l,t._getUIString("ScaleControl.Feet"));}else i&&"nautical"===i.unit?jr(e,o,s/1852,t._getUIString("ScaleControl.NauticalMiles")):s>=1e3?jr(e,o,s/1e3,t._getUIString("ScaleControl.Kilometers")):jr(e,o,s,t._getUIString("ScaleControl.Meters"));}function jr(t,e,i,o){var r,a,n,s=(r=i,(a=Math.pow(10,(""+Math.floor(r)).length-1))*(n=(n=r/a)>=10?10:n>=5?5:n>=3?3:n>=2?2:n>=1?1:function(t){var e=Math.pow(10,Math.ceil(-Math.log(t)/Math.LN10));return Math.round(t*e)/e}(n)));t.style.width=e*(s/i)+"px",t.innerHTML=s+" "+o;}Nr.prototype.getDefaultPosition=function(){return "bottom-left"},Nr.prototype._onMove=function(){Zr(this._map,this._container,this.options);},Nr.prototype.onAdd=function(t){return this._map=t,this._container=i.create("div","mapboxgl-ctrl mapboxgl-ctrl-scale",t.getContainer()),this._map.on("move",this._onMove),this._onMove(),this._container},Nr.prototype.onRemove=function(){i.remove(this._container),this._map.off("move",this._onMove),this._map=void 0;},Nr.prototype.setUnit=function(t){this.options.unit=t,Zr(this._map,this._container,this.options);};var qr=function(e){this._fullscreen=!1,e&&e.container&&(e.container instanceof t.window.HTMLElement?this._container=e.container:t.warnOnce("Full screen control 'container' must be a DOM element.")),t.bindAll(["_onClickFullscreen","_changeIcon"],this),"onfullscreenchange"in t.window.document?this._fullscreenchange="fullscreenchange":"onmozfullscreenchange"in t.window.document?this._fullscreenchange="mozfullscreenchange":"onwebkitfullscreenchange"in t.window.document?this._fullscreenchange="webkitfullscreenchange":"onmsfullscreenchange"in t.window.document&&(this._fullscreenchange="MSFullscreenChange");};qr.prototype.onAdd=function(e){return this._map=e,this._container||(this._container=this._map.getContainer()),this._controlContainer=i.create("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._checkFullscreenSupport()?this._setupUI():(this._controlContainer.style.display="none",t.warnOnce("This device does not support fullscreen mode.")),this._controlContainer},qr.prototype.onRemove=function(){i.remove(this._controlContainer),this._map=null,t.window.document.removeEventListener(this._fullscreenchange,this._changeIcon);},qr.prototype._checkFullscreenSupport=function(){return !!(t.window.document.fullscreenEnabled||t.window.document.mozFullScreenEnabled||t.window.document.msFullscreenEnabled||t.window.document.webkitFullscreenEnabled)},qr.prototype._setupUI=function(){var e=this._fullscreenButton=i.create("button","mapboxgl-ctrl-fullscreen",this._controlContainer);i.create("span","mapboxgl-ctrl-icon",e).setAttribute("aria-hidden",!0),e.type="button",this._updateTitle(),this._fullscreenButton.addEventListener("click",this._onClickFullscreen),t.window.document.addEventListener(this._fullscreenchange,this._changeIcon);},qr.prototype._updateTitle=function(){var t=this._getTitle();this._fullscreenButton.setAttribute("aria-label",t),this._fullscreenButton.title=t;},qr.prototype._getTitle=function(){return this._map._getUIString(this._isFullscreen()?"FullscreenControl.Exit":"FullscreenControl.Enter")},qr.prototype._isFullscreen=function(){return this._fullscreen},qr.prototype._changeIcon=function(){(t.window.document.fullscreenElement||t.window.document.mozFullScreenElement||t.window.document.webkitFullscreenElement||t.window.document.msFullscreenElement)===this._container!==this._fullscreen&&(this._fullscreen=!this._fullscreen,this._fullscreenButton.classList.toggle("mapboxgl-ctrl-shrink"),this._fullscreenButton.classList.toggle("mapboxgl-ctrl-fullscreen"),this._updateTitle());},qr.prototype._onClickFullscreen=function(){this._isFullscreen()?t.window.document.exitFullscreen?t.window.document.exitFullscreen():t.window.document.mozCancelFullScreen?t.window.document.mozCancelFullScreen():t.window.document.msExitFullscreen?t.window.document.msExitFullscreen():t.window.document.webkitCancelFullScreen&&t.window.document.webkitCancelFullScreen():this._container.requestFullscreen?this._container.requestFullscreen():this._container.mozRequestFullScreen?this._container.mozRequestFullScreen():this._container.msRequestFullscreen?this._container.msRequestFullscreen():this._container.webkitRequestFullscreen&&this._container.webkitRequestFullscreen();};var Vr={closeButton:!0,closeOnClick:!0,className:"",maxWidth:"240px"},Gr=function(e){function o(i){e.call(this),this.options=t.extend(Object.create(Vr),i),t.bindAll(["_update","_onClose","remove","_onMouseMove","_onMouseUp","_onDrag"],this);}return e&&(o.__proto__=e),(o.prototype=Object.create(e&&e.prototype)).constructor=o,o.prototype.addTo=function(e){return this._map&&this.remove(),this._map=e,this.options.closeOnClick&&this._map.on("click",this._onClose),this.options.closeOnMove&&this._map.on("move",this._onClose),this._map.on("remove",this.remove),this._update(),this._trackPointer?(this._map.on("mousemove",this._onMouseMove),this._map.on("mouseup",this._onMouseUp),this._container&&this._container.classList.add("mapboxgl-popup-track-pointer"),this._map._canvasContainer.classList.add("mapboxgl-track-pointer")):this._map.on("move",this._update),this.fire(new t.Event("open")),this},o.prototype.isOpen=function(){return !!this._map},o.prototype.remove=function(){return this._content&&i.remove(this._content),this._container&&(i.remove(this._container),delete this._container),this._map&&(this._map.off("move",this._update),this._map.off("move",this._onClose),this._map.off("click",this._onClose),this._map.off("remove",this.remove),this._map.off("mousemove",this._onMouseMove),this._map.off("mouseup",this._onMouseUp),this._map.off("drag",this._onDrag),delete this._map),this.fire(new t.Event("close")),this},o.prototype.getLngLat=function(){return this._lngLat},o.prototype.setLngLat=function(e){return this._lngLat=t.LngLat.convert(e),this._pos=null,this._trackPointer=!1,this._update(),this._map&&(this._map.on("move",this._update),this._map.off("mousemove",this._onMouseMove),this._container&&this._container.classList.remove("mapboxgl-popup-track-pointer"),this._map._canvasContainer.classList.remove("mapboxgl-track-pointer")),this},o.prototype.trackPointer=function(){return this._trackPointer=!0,this._pos=null,this._update(),this._map&&(this._map.off("move",this._update),this._map.on("mousemove",this._onMouseMove),this._map.on("drag",this._onDrag),this._container&&this._container.classList.add("mapboxgl-popup-track-pointer"),this._map._canvasContainer.classList.add("mapboxgl-track-pointer")),this},o.prototype.getElement=function(){return this._container},o.prototype.setText=function(e){return this.setDOMContent(t.window.document.createTextNode(e))},o.prototype.setHTML=function(e){var i,o=t.window.document.createDocumentFragment(),r=t.window.document.createElement("body");for(r.innerHTML=e;i=r.firstChild;)o.appendChild(i);return this.setDOMContent(o)},o.prototype.getMaxWidth=function(){return this._container&&this._container.style.maxWidth},o.prototype.setMaxWidth=function(t){return this.options.maxWidth=t,this._update(),this},o.prototype.setDOMContent=function(t){return this._createContent(),this._content.appendChild(t),this._update(),this},o.prototype.addClassName=function(t){this._container&&this._container.classList.add(t);},o.prototype.removeClassName=function(t){this._container&&this._container.classList.remove(t);},o.prototype.toggleClassName=function(t){if(this._container)return this._container.classList.toggle(t)},o.prototype._createContent=function(){this._content&&i.remove(this._content),this._content=i.create("div","mapboxgl-popup-content",this._container),this.options.closeButton&&(this._closeButton=i.create("button","mapboxgl-popup-close-button",this._content),this._closeButton.type="button",this._closeButton.setAttribute("aria-label","Close popup"),this._closeButton.innerHTML="×",this._closeButton.addEventListener("click",this._onClose));},o.prototype._onMouseUp=function(t){this._update(t.point);},o.prototype._onMouseMove=function(t){this._update(t.point);},o.prototype._onDrag=function(t){this._update(t.point);},o.prototype._update=function(e){var o=this;if(this._map&&(this._lngLat||this._trackPointer)&&this._content&&(this._container||(this._container=i.create("div","mapboxgl-popup",this._map.getContainer()),this._tip=i.create("div","mapboxgl-popup-tip",this._container),this._container.appendChild(this._content),this.options.className&&this.options.className.split(" ").forEach((function(t){return o._container.classList.add(t)})),this._trackPointer&&this._container.classList.add("mapboxgl-popup-track-pointer")),this.options.maxWidth&&this._container.style.maxWidth!==this.options.maxWidth&&(this._container.style.maxWidth=this.options.maxWidth),this._map.transform.renderWorldCopies&&!this._trackPointer&&(this._lngLat=Dr(this._lngLat,this._pos,this._map.transform)),!this._trackPointer||e)){var r=this._pos=this._trackPointer&&e?e:this._map.project(this._lngLat),a=this.options.anchor,n=function e(i){if(i){if("number"==typeof i){var o=Math.round(Math.sqrt(.5*Math.pow(i,2)));return {center:new t.Point(0,0),top:new t.Point(0,i),"top-left":new t.Point(o,o),"top-right":new t.Point(-o,o),bottom:new t.Point(0,-i),"bottom-left":new t.Point(o,-o),"bottom-right":new t.Point(-o,-o),left:new t.Point(i,0),right:new t.Point(-i,0)}}if(i instanceof t.Point||Array.isArray(i)){var r=t.Point.convert(i);return {center:r,top:r,"top-left":r,"top-right":r,bottom:r,"bottom-left":r,"bottom-right":r,left:r,right:r}}return {center:t.Point.convert(i.center||[0,0]),top:t.Point.convert(i.top||[0,0]),"top-left":t.Point.convert(i["top-left"]||[0,0]),"top-right":t.Point.convert(i["top-right"]||[0,0]),bottom:t.Point.convert(i.bottom||[0,0]),"bottom-left":t.Point.convert(i["bottom-left"]||[0,0]),"bottom-right":t.Point.convert(i["bottom-right"]||[0,0]),left:t.Point.convert(i.left||[0,0]),right:t.Point.convert(i.right||[0,0])}}return e(new t.Point(0,0))}(this.options.offset);if(!a){var s,l=this._container.offsetWidth,c=this._container.offsetHeight;s=r.y+n.bottom.ythis._map.transform.height-c?["bottom"]:[],r.xthis._map.transform.width-l/2&&s.push("right"),a=0===s.length?"bottom":s.join("-");}var u=r.add(n[a]).round();i.setTransform(this._container,Mr[a]+" translate("+u.x+"px,"+u.y+"px)"),Lr(this._container,a,"popup");}},o.prototype._onClose=function(){this.remove();},o}(t.Evented),Wr={version:t.version,supported:e,setRTLTextPlugin:t.setRTLTextPlugin,getRTLTextPluginStatus:t.getRTLTextPluginStatus,Map:Ir,NavigationControl:Cr,GeolocateControl:Fr,AttributionControl:gr,ScaleControl:Nr,FullscreenControl:qr,Popup:Gr,Marker:Rr,Style:qe,LngLat:t.LngLat,LngLatBounds:t.LngLatBounds,Point:t.Point,MercatorCoordinate:t.MercatorCoordinate,Evented:t.Evented,config:t.config,prewarm:function(){Ft().acquire(Rt);},clearPrewarmedResources:function(){var t=Bt;t&&(t.isPreloaded()&&1===t.numActive()?(t.release(Rt),Bt=null):console.warn("Could not clear WebWorkers since there are active Map instances that still reference it. The pre-warmed WebWorker pool can only be cleared when all map instances have been removed with map.remove()"));},get accessToken(){return t.config.ACCESS_TOKEN},set accessToken(e){t.config.ACCESS_TOKEN=e;},get baseApiUrl(){return t.config.API_URL},set baseApiUrl(e){t.config.API_URL=e;},get workerCount(){return kt.workerCount},set workerCount(t){kt.workerCount=t;},get maxParallelImageRequests(){return t.config.MAX_PARALLEL_IMAGE_REQUESTS},set maxParallelImageRequests(e){t.config.MAX_PARALLEL_IMAGE_REQUESTS=e;},clearStorage:function(e){t.clearTileCache(e);},workerUrl:""};return Wr})); // return mapboxgl; }))); //# sourceMappingURL=mapbox-gl.js.map /***/ }), /* 33 */ /***/ (function(module, exports) { var g; // This works in non-strict mode g = (function() { return this; })(); try { // This works if eval is allowed (see CSP) g = g || new Function("return this")(); } catch (e) { // This works if the window reference is available if (typeof window === "object") g = window; } // g can still be undefined, but nothing to do about it... // We return undefined, instead of nothing here, so it's // easier to handle this case. if(!global) { ...} module.exports = g; /***/ }), /* 34 */ /***/ (function(module, exports) { function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } module.exports = _interopRequireDefault; /***/ }), /* 35 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; // We need to centralize the zIndex definitions as they work // like global values in the browser. var zIndex = { mobileStepper: 1000, speedDial: 1050, appBar: 1100, drawer: 1200, modal: 1300, snackbar: 1400, tooltip: 1500 }; /* harmony default export */ __webpack_exports__["a"] = (zIndex); /***/ }), /* 36 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0); /* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__); var ThemeContext = react__WEBPACK_IMPORTED_MODULE_0___default.a.createContext(null); if (false) {} /* harmony default export */ __webpack_exports__["a"] = (ThemeContext); /***/ }), /* 37 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; var hasSymbol = typeof Symbol === 'function' && Symbol.for; /* harmony default export */ __webpack_exports__["a"] = (hasSymbol ? Symbol.for('mui.nested') : '__THEME_NESTED__'); /***/ }), /* 38 */ /***/ (function(module, exports, __webpack_require__) { var objectKeys = __webpack_require__(53); var isArguments = __webpack_require__(55); var is = __webpack_require__(97); var isRegex = __webpack_require__(98); var flags = __webpack_require__(101); var isArray = __webpack_require__(103); var isDate = __webpack_require__(104); var whichBoxedPrimitive = __webpack_require__(105); var GetIntrinsic = __webpack_require__(30); var callBound = __webpack_require__(43); var whichCollection = __webpack_require__(110); var getIterator = __webpack_require__(113); var getSideChannel = __webpack_require__(116); var $getTime = callBound('Date.prototype.getTime'); var gPO = Object.getPrototypeOf; var $objToString = callBound('Object.prototype.toString'); var $Set = GetIntrinsic('%Set%', true); var $mapHas = callBound('Map.prototype.has', true); var $mapGet = callBound('Map.prototype.get', true); var $mapSize = callBound('Map.prototype.size', true); var $setAdd = callBound('Set.prototype.add', true); var $setDelete = callBound('Set.prototype.delete', true); var $setHas = callBound('Set.prototype.has', true); var $setSize = callBound('Set.prototype.size', true); // taken from https://github.com/browserify/commonjs-assert/blob/bba838e9ba9e28edf3127ce6974624208502f6bc/internal/util/comparisons.js#L401-L414 function setHasEqualElement(set, val1, strict, channel) { var i = getIterator(set); var result; while ((result = i.next()) && !result.done) { if (internalDeepEqual(val1, result.value, strict, channel)) { // eslint-disable-line no-use-before-define // Remove the matching element to make sure we do not check that again. $setDelete(set, result.value); return true; } } return false; } // taken from https://github.com/browserify/commonjs-assert/blob/bba838e9ba9e28edf3127ce6974624208502f6bc/internal/util/comparisons.js#L416-L439 function findLooseMatchingPrimitives(prim) { if (typeof prim === 'undefined') { return null; } if (typeof prim === 'object') { // Only pass in null as object! return void 0; } if (typeof prim === 'symbol') { return false; } if (typeof prim === 'string' || typeof prim === 'number') { // Loose equal entries exist only if the string is possible to convert to a regular number and not NaN. return +prim === +prim; // eslint-disable-line no-implicit-coercion } return true; } // taken from https://github.com/browserify/commonjs-assert/blob/bba838e9ba9e28edf3127ce6974624208502f6bc/internal/util/comparisons.js#L449-L460 function mapMightHaveLoosePrim(a, b, prim, item, channel) { var altValue = findLooseMatchingPrimitives(prim); if (altValue != null) { return altValue; } var curB = $mapGet(b, altValue); // eslint-disable-next-line no-use-before-define if ((typeof curB === 'undefined' && !$mapHas(b, altValue)) || !internalDeepEqual(item, curB, false, channel)) { return false; } // eslint-disable-next-line no-use-before-define return !$mapHas(a, altValue) && internalDeepEqual(item, curB, false, channel); } // taken from https://github.com/browserify/commonjs-assert/blob/bba838e9ba9e28edf3127ce6974624208502f6bc/internal/util/comparisons.js#L441-L447 function setMightHaveLoosePrim(a, b, prim) { var altValue = findLooseMatchingPrimitives(prim); if (altValue != null) { return altValue; } return $setHas(b, altValue) && !$setHas(a, altValue); } // taken from https://github.com/browserify/commonjs-assert/blob/bba838e9ba9e28edf3127ce6974624208502f6bc/internal/util/comparisons.js#L518-L533 function mapHasEqualEntry(set, map, key1, item1, strict, channel) { var i = getIterator(set); var result; var key2; while ((result = i.next()) && !result.done) { key2 = result.value; if ( // eslint-disable-next-line no-use-before-define internalDeepEqual(key1, key2, strict, channel) // eslint-disable-next-line no-use-before-define && internalDeepEqual(item1, $mapGet(map, key2), strict, channel) ) { $setDelete(set, key2); return true; } } return false; } function internalDeepEqual(actual, expected, options, channel) { var opts = options || {}; // 7.1. All identical values are equivalent, as determined by ===. if (opts.strict ? is(actual, expected) : actual === expected) { return true; } var actualBoxed = whichBoxedPrimitive(actual); var expectedBoxed = whichBoxedPrimitive(expected); if (actualBoxed !== expectedBoxed) { return false; } // 7.3. Other pairs that do not both pass typeof value == 'object', equivalence is determined by ==. if (!actual || !expected || (typeof actual !== 'object' && typeof expected !== 'object')) { if ((actual === false && expected) || (actual && expected === false)) { return false; } return opts.strict ? is(actual, expected) : actual == expected; // eslint-disable-line eqeqeq } /* * 7.4. For all other Object pairs, including Array objects, equivalence is * determined by having the same number of owned properties (as verified * with Object.prototype.hasOwnProperty.call), the same set of keys * (although not necessarily the same order), equivalent values for every * corresponding key, and an identical 'prototype' property. Note: this * accounts for both named and indexed properties on Arrays. */ // see https://github.com/nodejs/node/commit/d3aafd02efd3a403d646a3044adcf14e63a88d32 for memos/channel inspiration var hasActual = channel.has(actual); var hasExpected = channel.has(expected); var sentinel; if (hasActual && hasExpected) { if (channel.get(actual) === channel.get(expected)) { return true; } } else { sentinel = {}; } if (!hasActual) { channel.set(actual, sentinel); } if (!hasExpected) { channel.set(expected, sentinel); } // eslint-disable-next-line no-use-before-define return objEquiv(actual, expected, opts, channel); } function isBuffer(x) { if (!x || typeof x !== 'object' || typeof x.length !== 'number') { return false; } if (typeof x.copy !== 'function' || typeof x.slice !== 'function') { return false; } if (x.length > 0 && typeof x[0] !== 'number') { return false; } return true; } function setEquiv(a, b, opts, channel) { if ($setSize(a) !== $setSize(b)) { return false; } var iA = getIterator(a); var iB = getIterator(b); var resultA; var resultB; var set; while ((resultA = iA.next()) && !resultA.done) { if (resultA.value && typeof resultA.value === 'object') { if (!set) { set = new $Set(); } $setAdd(set, resultA.value); } else if (!$setHas(b, resultA.value)) { if (opts.strict) { return false; } if (!setMightHaveLoosePrim(a, b, resultA.value)) { return false; } if (!set) { set = new $Set(); } $setAdd(set, resultA.value); } } if (set) { while ((resultB = iB.next()) && !resultB.done) { // We have to check if a primitive value is already matching and only if it's not, go hunting for it. if (resultB.value && typeof resultB.value === 'object') { if (!setHasEqualElement(set, resultB.value, opts.strict, channel)) { return false; } } else if ( !opts.strict && !$setHas(a, resultB.value) && !setHasEqualElement(set, resultB.value, opts.strict, channel) ) { return false; } } return $setSize(set) === 0; } return true; } function mapEquiv(a, b, opts, channel) { if ($mapSize(a) !== $mapSize(b)) { return false; } var iA = getIterator(a); var iB = getIterator(b); var resultA; var resultB; var set; var key; var item1; var item2; while ((resultA = iA.next()) && !resultA.done) { key = resultA.value[0]; item1 = resultA.value[1]; if (key && typeof key === 'object') { if (!set) { set = new $Set(); } $setAdd(set, key); } else { item2 = $mapGet(b, key); // if (typeof curB === 'undefined' && !$mapHas(b, altValue) || !internalDeepEqual(item, curB, false, channel)) { if ((typeof item2 === 'undefined' && !$mapHas(b, key)) || !internalDeepEqual(item1, item2, opts.strict, channel)) { if (opts.strict) { return false; } if (!mapMightHaveLoosePrim(a, b, key, item1, channel)) { return false; } if (!set) { set = new $Set(); } $setAdd(set, key); } } } if (set) { while ((resultB = iB.next()) && !resultB.done) { key = resultB.value[0]; item1 = resultB.value[1]; if (key && typeof key === 'object') { if (!mapHasEqualEntry(set, a, key, item1, opts.strict, channel)) { return false; } } else if ( !opts.strict && (!a.has(key) || !internalDeepEqual($mapGet(a, key), item1, false, channel)) && !mapHasEqualEntry(set, a, key, item1, false, channel) ) { return false; } } return $setSize(set) === 0; } return true; } function objEquiv(a, b, opts, channel) { /* eslint max-statements: [2, 100], max-lines-per-function: [2, 120], max-depth: [2, 5] */ var i, key; if (typeof a !== typeof b) { return false; } if (a == null || b == null) { return false; } // an identical 'prototype' property. if (a.prototype !== b.prototype) { return false; } if ($objToString(a) !== $objToString(b)) { return false; } if (isArguments(a) !== isArguments(b)) { return false; } var aIsArray = isArray(a); var bIsArray = isArray(b); if (aIsArray !== bIsArray) { return false; } // TODO: replace when a cross-realm brand check is available var aIsError = a instanceof Error; var bIsError = b instanceof Error; if (aIsError !== bIsError) { return false; } if (aIsError || bIsError) { if (a.name !== b.name || a.message !== b.message) { return false; } } var aIsRegex = isRegex(a); var bIsRegex = isRegex(b); if (aIsRegex !== bIsRegex) { return false; } if ((aIsRegex || bIsRegex) && (a.source !== b.source || flags(a) !== flags(b))) { return false; } var aIsDate = isDate(a); var bIsDate = isDate(b); if (aIsDate !== bIsDate) { return false; } if (aIsDate || bIsDate) { // && would work too, because both are true or both false here if ($getTime(a) !== $getTime(b)) { return false; } } if (opts.strict && gPO && gPO(a) !== gPO(b)) { return false; } var aIsBuffer = isBuffer(a); var bIsBuffer = isBuffer(b); if (aIsBuffer !== bIsBuffer) { return false; } if (aIsBuffer || bIsBuffer) { // && would work too, because both are true or both false here if (a.length !== b.length) { return false; } for (i = 0; i < a.length; i++) { if (a[i] !== b[i]) { return false; } } return true; } if (typeof a !== typeof b) { return false; } try { var ka = objectKeys(a); var kb = objectKeys(b); } catch (e) { // happens when one is a string literal and the other isn't return false; } // having the same number of owned properties (keys incorporates hasOwnProperty) if (ka.length !== kb.length) { return false; } // the same set of keys (although not necessarily the same order), ka.sort(); kb.sort(); // ~~~cheap key test for (i = ka.length - 1; i >= 0; i--) { if (ka[i] != kb[i]) { return false; } // eslint-disable-line eqeqeq } // equivalent values for every corresponding key, and ~~~possibly expensive deep test for (i = ka.length - 1; i >= 0; i--) { key = ka[i]; if (!internalDeepEqual(a[key], b[key], opts, channel)) { return false; } } var aCollection = whichCollection(a); var bCollection = whichCollection(b); if (aCollection !== bCollection) { return false; } if (aCollection === 'Set' || bCollection === 'Set') { // aCollection === bCollection return setEquiv(a, b, opts, channel); } if (aCollection === 'Map') { // aCollection === bCollection return mapEquiv(a, b, opts, channel); } return true; } module.exports = function deepEqual(a, b, opts) { return internalDeepEqual(a, b, opts, getSideChannel()); }; /***/ }), /* 39 */, /* 40 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var implementation = __webpack_require__(100); module.exports = Function.prototype.bind || implementation; /***/ }), /* 41 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var keys = __webpack_require__(53); var hasSymbols = typeof Symbol === 'function' && typeof Symbol('foo') === 'symbol'; var toStr = Object.prototype.toString; var concat = Array.prototype.concat; var origDefineProperty = Object.defineProperty; var isFunction = function (fn) { return typeof fn === 'function' && toStr.call(fn) === '[object Function]'; }; var arePropertyDescriptorsSupported = function () { var obj = {}; try { origDefineProperty(obj, 'x', { enumerable: false, value: obj }); // eslint-disable-next-line no-unused-vars, no-restricted-syntax for (var _ in obj) { // jscs:ignore disallowUnusedVariables return false; } return obj.x === obj; } catch (e) { /* this is IE 8. */ return false; } }; var supportsDescriptors = origDefineProperty && arePropertyDescriptorsSupported(); var defineProperty = function (object, name, value, predicate) { if (name in object && (!isFunction(predicate) || !predicate())) { return; } if (supportsDescriptors) { origDefineProperty(object, name, { configurable: true, enumerable: false, value: value, writable: true }); } else { object[name] = value; } }; var defineProperties = function (object, map) { var predicates = arguments.length > 2 ? arguments[2] : {}; var props = keys(map); if (hasSymbols) { props = concat.call(props, Object.getOwnPropertySymbols(map)); } for (var i = 0; i < props.length; i += 1) { defineProperty(object, props[i], map[props[i]], predicates[props[i]]); } }; defineProperties.supportsDescriptors = !!supportsDescriptors; module.exports = defineProperties; /***/ }), /* 42 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* WEBPACK VAR INJECTION */(function(global) { var origSymbol = global.Symbol; var hasSymbolSham = __webpack_require__(57); module.exports = function hasNativeSymbols() { if (typeof origSymbol !== 'function') { return false; } if (typeof Symbol !== 'function') { return false; } if (typeof origSymbol('foo') !== 'symbol') { return false; } if (typeof Symbol('bar') !== 'symbol') { return false; } return hasSymbolSham(); }; /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(33))) /***/ }), /* 43 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var GetIntrinsic = __webpack_require__(30); var callBind = __webpack_require__(56); var $indexOf = callBind(GetIntrinsic('String.prototype.indexOf')); module.exports = function callBoundIntrinsic(name, allowMissing) { var intrinsic = GetIntrinsic(name, !!allowMissing); if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.')) { return callBind(intrinsic); } return intrinsic; }; /***/ }), /* 44 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var _interopRequireDefault = __webpack_require__(34); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = createSvgIcon; var _extends2 = _interopRequireDefault(__webpack_require__(121)); var _react = _interopRequireDefault(__webpack_require__(0)); var _SvgIcon = _interopRequireDefault(__webpack_require__(45)); function createSvgIcon(path, displayName) { var Component = _react.default.memo(_react.default.forwardRef(function (props, ref) { return _react.default.createElement(_SvgIcon.default, (0, _extends2.default)({ ref: ref }, props), path); })); if (false) {} Component.muiName = _SvgIcon.default.muiName; return Component; } /***/ }), /* 45 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _SvgIcon__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(63); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "default", function() { return _SvgIcon__WEBPACK_IMPORTED_MODULE_0__["a"]; }); /***/ }), /* 46 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; 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 getMergeFunction(key, options) { if (!options.customMerge) { return deepmerge } var customMerge = options.customMerge(key); return typeof customMerge === 'function' ? customMerge : deepmerge } function getEnumerableOwnPropertySymbols(target) { return Object.getOwnPropertySymbols ? Object.getOwnPropertySymbols(target).filter(function(symbol) { return target.propertyIsEnumerable(symbol) }) : [] } function getKeys(target) { return Object.keys(target).concat(getEnumerableOwnPropertySymbols(target)) } function propertyIsOnObject(object, property) { try { return property in object } catch(_) { return false } } // Protects from prototype poisoning and unexpected merging up the prototype chain. function propertyIsUnsafe(target, key) { return propertyIsOnObject(target, key) // Properties are safe to merge if they don't exist in the target yet, && !(Object.hasOwnProperty.call(target, key) // unsafe if they exist up the prototype chain, && Object.propertyIsEnumerable.call(target, key)) // and also unsafe if they're nonenumerable. } function mergeObject(target, source, options) { var destination = {}; if (options.isMergeableObject(target)) { getKeys(target).forEach(function(key) { destination[key] = cloneUnlessOtherwiseSpecified(target[key], options); }); } getKeys(source).forEach(function(key) { if (propertyIsUnsafe(target, key)) { return } if (propertyIsOnObject(target, key) && options.isMergeableObject(source[key])) { destination[key] = getMergeFunction(key, options)(target[key], source[key], options); } else { destination[key] = cloneUnlessOtherwiseSpecified(source[key], options); } }); return destination } function deepmerge(target, source, options) { options = options || {}; options.arrayMerge = options.arrayMerge || defaultArrayMerge; options.isMergeableObject = options.isMergeableObject || isMergeableObject; // cloneUnlessOtherwiseSpecified is added to `options` so that custom arrayMerge() // implementations can use it. The caller may not replace it. options.cloneUnlessOtherwiseSpecified = cloneUnlessOtherwiseSpecified; 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; module.exports = deepmerge_1; /***/ }), /* 47 */, /* 48 */, /* 49 */, /* 50 */, /* 51 */, /* 52 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* object-assign (c) Sindre Sorhus @license MIT */ /* eslint-disable no-unused-vars */ var getOwnPropertySymbols = Object.getOwnPropertySymbols; var hasOwnProperty = Object.prototype.hasOwnProperty; var propIsEnumerable = Object.prototype.propertyIsEnumerable; function toObject(val) { if (val === null || val === undefined) { throw new TypeError('Object.assign cannot be called with null or undefined'); } return Object(val); } function shouldUseNative() { try { if (!Object.assign) { return false; } // Detect buggy property enumeration order in older V8 versions. // https://bugs.chromium.org/p/v8/issues/detail?id=4118 var test1 = new String('abc'); // eslint-disable-line no-new-wrappers test1[5] = 'de'; if (Object.getOwnPropertyNames(test1)[0] === '5') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test2 = {}; for (var i = 0; i < 10; i++) { test2['_' + String.fromCharCode(i)] = i; } var order2 = Object.getOwnPropertyNames(test2).map(function (n) { return test2[n]; }); if (order2.join('') !== '0123456789') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test3 = {}; 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { test3[letter] = letter; }); if (Object.keys(Object.assign({}, test3)).join('') !== 'abcdefghijklmnopqrst') { return false; } return true; } catch (err) { // We don't expect any of the above to throw, but better to be safe. return false; } } module.exports = shouldUseNative() ? Object.assign : function (target, source) { var from; var to = toObject(target); var symbols; for (var s = 1; s < arguments.length; s++) { from = Object(arguments[s]); for (var key in from) { if (hasOwnProperty.call(from, key)) { to[key] = from[key]; } } if (getOwnPropertySymbols) { symbols = getOwnPropertySymbols(from); for (var i = 0; i < symbols.length; i++) { if (propIsEnumerable.call(from, symbols[i])) { to[symbols[i]] = from[symbols[i]]; } } } } return to; }; /***/ }), /* 53 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var slice = Array.prototype.slice; var isArgs = __webpack_require__(54); var origKeys = Object.keys; var keysShim = origKeys ? function keys(o) { return origKeys(o); } : __webpack_require__(96); var originalKeys = Object.keys; keysShim.shim = function shimObjectKeys() { if (Object.keys) { var keysWorksWithArguments = (function () { // Safari 5.0 bug var args = Object.keys(arguments); return args && args.length === arguments.length; }(1, 2)); if (!keysWorksWithArguments) { Object.keys = function keys(object) { // eslint-disable-line func-name-matching if (isArgs(object)) { return originalKeys(slice.call(object)); } return originalKeys(object); }; } } else { Object.keys = keysShim; } return Object.keys || keysShim; }; module.exports = keysShim; /***/ }), /* 54 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var toStr = Object.prototype.toString; module.exports = function isArguments(value) { var str = toStr.call(value); var isArgs = str === '[object Arguments]'; if (!isArgs) { isArgs = str !== '[object Array]' && value !== null && typeof value === 'object' && typeof value.length === 'number' && value.length >= 0 && toStr.call(value.callee) === '[object Function]'; } return isArgs; }; /***/ }), /* 55 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; var toStr = Object.prototype.toString; var isStandardArguments = function isArguments(value) { if (hasToStringTag && value && typeof value === 'object' && Symbol.toStringTag in value) { return false; } return toStr.call(value) === '[object Arguments]'; }; var isLegacyArguments = function isArguments(value) { if (isStandardArguments(value)) { return true; } return value !== null && typeof value === 'object' && typeof value.length === 'number' && value.length >= 0 && toStr.call(value) !== '[object Array]' && toStr.call(value.callee) === '[object Function]'; }; var supportsStandardArguments = (function () { return isStandardArguments(arguments); }()); isStandardArguments.isLegacyArguments = isLegacyArguments; // for tests module.exports = supportsStandardArguments ? isStandardArguments : isLegacyArguments; /***/ }), /* 56 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var bind = __webpack_require__(40); var GetIntrinsic = __webpack_require__(30); var $Function = GetIntrinsic('%Function%'); var $apply = $Function.apply; var $call = $Function.call; module.exports = function callBind() { return bind.apply($call, arguments); }; module.exports.apply = function applyBind() { return bind.apply($apply, arguments); }; /***/ }), /* 57 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* eslint complexity: [2, 18], max-statements: [2, 33] */ module.exports = function hasSymbols() { if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; } if (typeof Symbol.iterator === 'symbol') { return true; } var obj = {}; var sym = Symbol('test'); var symObj = Object(sym); if (typeof sym === 'string') { return false; } if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; } if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; } // temp disabled per https://github.com/ljharb/object.assign/issues/17 // if (sym instanceof Symbol) { return false; } // temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4 // if (!(symObj instanceof Symbol)) { return false; } // if (typeof Symbol.prototype.toString !== 'function') { return false; } // if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; } var symVal = 42; obj[sym] = symVal; for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; } if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; } var syms = Object.getOwnPropertySymbols(obj); if (syms.length !== 1 || syms[0] !== sym) { return false; } if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; } if (typeof Object.getOwnPropertyDescriptor === 'function') { var descriptor = Object.getOwnPropertyDescriptor(obj, sym); if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; } } return true; }; /***/ }), /* 58 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var $Object = Object; var $TypeError = TypeError; module.exports = function flags() { if (this != null && this !== $Object(this)) { throw new $TypeError('RegExp.prototype.flags getter called on non-object'); } var result = ''; if (this.global) { result += 'g'; } if (this.ignoreCase) { result += 'i'; } if (this.multiline) { result += 'm'; } if (this.dotAll) { result += 's'; } if (this.unicode) { result += 'u'; } if (this.sticky) { result += 'y'; } return result; }; /***/ }), /* 59 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var implementation = __webpack_require__(58); var supportsDescriptors = __webpack_require__(41).supportsDescriptors; var $gOPD = Object.getOwnPropertyDescriptor; var $TypeError = TypeError; module.exports = function getPolyfill() { if (!supportsDescriptors) { throw new $TypeError('RegExp.prototype.flags requires a true ES5 environment that supports property descriptors'); } if ((/a/mig).flags === 'gim') { var descriptor = $gOPD(RegExp.prototype, 'flags'); if (descriptor && typeof descriptor.get === 'function' && typeof (/a/).dotAll === 'boolean') { return descriptor.get; } } return implementation; }; /***/ }), /* 60 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var strValue = String.prototype.valueOf; var tryStringObject = function tryStringObject(value) { try { strValue.call(value); return true; } catch (e) { return false; } }; var toStr = Object.prototype.toString; var strClass = '[object String]'; var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; module.exports = function isString(value) { if (typeof value === 'string') { return true; } if (typeof value !== 'object') { return false; } return hasToStringTag ? tryStringObject(value) : toStr.call(value) === strClass; }; /***/ }), /* 61 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var $Map = typeof Map === 'function' && Map.prototype ? Map : null; var $Set = typeof Set === 'function' && Set.prototype ? Set : null; var exported; if (!$Map) { // eslint-disable-next-line no-unused-vars exported = function isMap(x) { // `Map` is not present in this environment. return false; }; } var $mapHas = $Map ? Map.prototype.has : null; var $setHas = $Set ? Set.prototype.has : null; if (!exported && !$mapHas) { // eslint-disable-next-line no-unused-vars exported = function isMap(x) { // `Map` does not have a `has` method return false; }; } module.exports = exported || function isMap(x) { if (!x || typeof x !== 'object') { return false; } try { $mapHas.call(x); if ($setHas) { try { $setHas.call(x); } catch (e) { return true; } } return x instanceof $Map; // core-js workaround, pre-v2.5.0 } catch (e) {} return false; }; /***/ }), /* 62 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var $Map = typeof Map === 'function' && Map.prototype ? Map : null; var $Set = typeof Set === 'function' && Set.prototype ? Set : null; var exported; if (!$Set) { // eslint-disable-next-line no-unused-vars exported = function isSet(x) { // `Set` is not present in this environment. return false; }; } var $mapHas = $Map ? Map.prototype.has : null; var $setHas = $Set ? Set.prototype.has : null; if (!exported && !$setHas) { // eslint-disable-next-line no-unused-vars exported = function isSet(x) { // `Set` does not have a `has` method return false; }; } module.exports = exported || function isSet(x) { if (!x || typeof x !== 'object') { return false; } try { $setHas.call(x); if ($mapHas) { try { $mapHas.call(x); } catch (e) { return true; } } return x instanceof $Set; // core-js workaround, pre-v2.5.0 } catch (e) {} return false; }; /***/ }), /* 63 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* unused harmony export styles */ /* harmony import */ var _babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2); /* harmony import */ var _babel_runtime_helpers_esm_objectWithoutProperties__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(4); /* harmony import */ var react__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(0); /* harmony import */ var react__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_2__); /* harmony import */ var prop_types__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1); /* harmony import */ var prop_types__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(prop_types__WEBPACK_IMPORTED_MODULE_3__); /* harmony import */ var clsx__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(5); /* harmony import */ var _styles_withStyles__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(6); /* harmony import */ var _utils_capitalize__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(7); var styles = function styles(theme) { return { /* Styles applied to the root element. */ root: { userSelect: 'none', width: '1em', height: '1em', display: 'inline-block', fill: 'currentColor', flexShrink: 0, fontSize: theme.typography.pxToRem(24), transition: theme.transitions.create('fill', { duration: theme.transitions.duration.shorter }) }, /* Styles applied to the root element if `color="primary"`. */ colorPrimary: { color: theme.palette.primary.main }, /* Styles applied to the root element if `color="secondary"`. */ colorSecondary: { color: theme.palette.secondary.main }, /* Styles applied to the root element if `color="action"`. */ colorAction: { color: theme.palette.action.active }, /* Styles applied to the root element if `color="error"`. */ colorError: { color: theme.palette.error.main }, /* Styles applied to the root element if `color="disabled"`. */ colorDisabled: { color: theme.palette.action.disabled }, /* Styles applied to the root element if `fontSize="inherit"`. */ fontSizeInherit: { fontSize: 'inherit' }, /* Styles applied to the root element if `fontSize="small"`. */ fontSizeSmall: { fontSize: theme.typography.pxToRem(20) }, /* Styles applied to the root element if `fontSize="large"`. */ fontSizeLarge: { fontSize: theme.typography.pxToRem(35) } }; }; var SvgIcon = react__WEBPACK_IMPORTED_MODULE_2___default.a.forwardRef(function SvgIcon(props, ref) { var children = props.children, classes = props.classes, className = props.className, _props$color = props.color, color = _props$color === void 0 ? 'inherit' : _props$color, _props$component = props.component, Component = _props$component === void 0 ? 'svg' : _props$component, _props$fontSize = props.fontSize, fontSize = _props$fontSize === void 0 ? 'default' : _props$fontSize, htmlColor = props.htmlColor, titleAccess = props.titleAccess, _props$viewBox = props.viewBox, viewBox = _props$viewBox === void 0 ? '0 0 24 24' : _props$viewBox, other = Object(_babel_runtime_helpers_esm_objectWithoutProperties__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"])(props, ["children", "classes", "className", "color", "component", "fontSize", "htmlColor", "titleAccess", "viewBox"]); return react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement(Component, Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"])({ className: Object(clsx__WEBPACK_IMPORTED_MODULE_4__[/* default */ "a"])(classes.root, className, color !== 'inherit' && classes["color".concat(Object(_utils_capitalize__WEBPACK_IMPORTED_MODULE_6__[/* default */ "a"])(color))], fontSize !== 'default' && classes["fontSize".concat(Object(_utils_capitalize__WEBPACK_IMPORTED_MODULE_6__[/* default */ "a"])(fontSize))]), focusable: "false", viewBox: viewBox, color: htmlColor, "aria-hidden": titleAccess ? undefined : 'true', role: titleAccess ? 'img' : 'presentation', ref: ref }, other), children, titleAccess ? react__WEBPACK_IMPORTED_MODULE_2___default.a.createElement("title", null, titleAccess) : null); }); false ? undefined : void 0; SvgIcon.muiName = 'SvgIcon'; /* harmony default export */ __webpack_exports__["a"] = (Object(_styles_withStyles__WEBPACK_IMPORTED_MODULE_5__[/* default */ "a"])(styles, { name: 'MuiSvgIcon' })(SvgIcon)); /***/ }), /* 64 */ /***/ (function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_RESULT__;/*! Hammer.JS - v2.0.7 - 2016-04-22 * http://hammerjs.github.io/ * * Copyright (c) 2016 Jorik Tangelder; * Licensed under the MIT license */ (function(window, document, exportName, undefined) { 'use strict'; var VENDOR_PREFIXES = ['', 'webkit', 'Moz', 'MS', 'ms', 'o']; var TEST_ELEMENT = document.createElement('div'); var TYPE_FUNCTION = 'function'; var round = Math.round; var abs = Math.abs; var now = Date.now; /** * set a timeout with a given scope * @param {Function} fn * @param {Number} timeout * @param {Object} context * @returns {number} */ function setTimeoutContext(fn, timeout, context) { return setTimeout(bindFn(fn, context), timeout); } /** * if the argument is an array, we want to execute the fn on each entry * if it aint an array we don't want to do a thing. * this is used by all the methods that accept a single and array argument. * @param {*|Array} arg * @param {String} fn * @param {Object} [context] * @returns {Boolean} */ function invokeArrayArg(arg, fn, context) { if (Array.isArray(arg)) { each(arg, context[fn], context); return true; } return false; } /** * walk objects and arrays * @param {Object} obj * @param {Function} iterator * @param {Object} context */ function each(obj, iterator, context) { var i; if (!obj) { return; } if (obj.forEach) { obj.forEach(iterator, context); } else if (obj.length !== undefined) { i = 0; while (i < obj.length) { iterator.call(context, obj[i], i, obj); i++; } } else { for (i in obj) { obj.hasOwnProperty(i) && iterator.call(context, obj[i], i, obj); } } } /** * wrap a method with a deprecation warning and stack trace * @param {Function} method * @param {String} name * @param {String} message * @returns {Function} A new function wrapping the supplied method. */ function deprecate(method, name, message) { var deprecationMessage = 'DEPRECATED METHOD: ' + name + '\n' + message + ' AT \n'; return function() { var e = new Error('get-stack-trace'); var stack = e && e.stack ? e.stack.replace(/^[^\(]+?[\n$]/gm, '') .replace(/^\s+at\s+/gm, '') .replace(/^Object.\s*\(/gm, '{anonymous}()@') : 'Unknown Stack Trace'; var log = window.console && (window.console.warn || window.console.log); if (log) { log.call(window.console, deprecationMessage, stack); } return method.apply(this, arguments); }; } /** * extend object. * means that properties in dest will be overwritten by the ones in src. * @param {Object} target * @param {...Object} objects_to_assign * @returns {Object} target */ var assign; if (typeof Object.assign !== 'function') { assign = function assign(target) { if (target === undefined || target === null) { throw new TypeError('Cannot convert undefined or null to object'); } var output = Object(target); for (var index = 1; index < arguments.length; index++) { var source = arguments[index]; if (source !== undefined && source !== null) { for (var nextKey in source) { if (source.hasOwnProperty(nextKey)) { output[nextKey] = source[nextKey]; } } } } return output; }; } else { assign = Object.assign; } /** * extend object. * means that properties in dest will be overwritten by the ones in src. * @param {Object} dest * @param {Object} src * @param {Boolean} [merge=false] * @returns {Object} dest */ var extend = deprecate(function extend(dest, src, merge) { var keys = Object.keys(src); var i = 0; while (i < keys.length) { if (!merge || (merge && dest[keys[i]] === undefined)) { dest[keys[i]] = src[keys[i]]; } i++; } return dest; }, 'extend', 'Use `assign`.'); /** * merge the values from src in the dest. * means that properties that exist in dest will not be overwritten by src * @param {Object} dest * @param {Object} src * @returns {Object} dest */ var merge = deprecate(function merge(dest, src) { return extend(dest, src, true); }, 'merge', 'Use `assign`.'); /** * simple class inheritance * @param {Function} child * @param {Function} base * @param {Object} [properties] */ function inherit(child, base, properties) { var baseP = base.prototype, childP; childP = child.prototype = Object.create(baseP); childP.constructor = child; childP._super = baseP; if (properties) { assign(childP, properties); } } /** * simple function bind * @param {Function} fn * @param {Object} context * @returns {Function} */ function bindFn(fn, context) { return function boundFn() { return fn.apply(context, arguments); }; } /** * let a boolean value also be a function that must return a boolean * this first item in args will be used as the context * @param {Boolean|Function} val * @param {Array} [args] * @returns {Boolean} */ function boolOrFn(val, args) { if (typeof val == TYPE_FUNCTION) { return val.apply(args ? args[0] || undefined : undefined, args); } return val; } /** * use the val2 when val1 is undefined * @param {*} val1 * @param {*} val2 * @returns {*} */ function ifUndefined(val1, val2) { return (val1 === undefined) ? val2 : val1; } /** * addEventListener with multiple events at once * @param {EventTarget} target * @param {String} types * @param {Function} handler */ function addEventListeners(target, types, handler) { each(splitStr(types), function(type) { target.addEventListener(type, handler, false); }); } /** * removeEventListener with multiple events at once * @param {EventTarget} target * @param {String} types * @param {Function} handler */ function removeEventListeners(target, types, handler) { each(splitStr(types), function(type) { target.removeEventListener(type, handler, false); }); } /** * find if a node is in the given parent * @method hasParent * @param {HTMLElement} node * @param {HTMLElement} parent * @return {Boolean} found */ function hasParent(node, parent) { while (node) { if (node == parent) { return true; } node = node.parentNode; } return false; } /** * small indexOf wrapper * @param {String} str * @param {String} find * @returns {Boolean} found */ function inStr(str, find) { return str.indexOf(find) > -1; } /** * split string on whitespace * @param {String} str * @returns {Array} words */ function splitStr(str) { return str.trim().split(/\s+/g); } /** * find if a array contains the object using indexOf or a simple polyFill * @param {Array} src * @param {String} find * @param {String} [findByKey] * @return {Boolean|Number} false when not found, or the index */ function inArray(src, find, findByKey) { if (src.indexOf && !findByKey) { return src.indexOf(find); } else { var i = 0; while (i < src.length) { if ((findByKey && src[i][findByKey] == find) || (!findByKey && src[i] === find)) { return i; } i++; } return -1; } } /** * convert array-like objects to real arrays * @param {Object} obj * @returns {Array} */ function toArray(obj) { return Array.prototype.slice.call(obj, 0); } /** * unique array with objects based on a key (like 'id') or just by the array's value * @param {Array} src [{id:1},{id:2},{id:1}] * @param {String} [key] * @param {Boolean} [sort=False] * @returns {Array} [{id:1},{id:2}] */ function uniqueArray(src, key, sort) { var results = []; var values = []; var i = 0; while (i < src.length) { var val = key ? src[i][key] : src[i]; if (inArray(values, val) < 0) { results.push(src[i]); } values[i] = val; i++; } if (sort) { if (!key) { results = results.sort(); } else { results = results.sort(function sortUniqueArray(a, b) { return a[key] > b[key]; }); } } return results; } /** * get the prefixed property * @param {Object} obj * @param {String} property * @returns {String|Undefined} prefixed */ function prefixed(obj, property) { var prefix, prop; var camelProp = property[0].toUpperCase() + property.slice(1); var i = 0; while (i < VENDOR_PREFIXES.length) { prefix = VENDOR_PREFIXES[i]; prop = (prefix) ? prefix + camelProp : property; if (prop in obj) { return prop; } i++; } return undefined; } /** * get a unique id * @returns {number} uniqueId */ var _uniqueId = 1; function uniqueId() { return _uniqueId++; } /** * get the window object of an element * @param {HTMLElement} element * @returns {DocumentView|Window} */ function getWindowForElement(element) { var doc = element.ownerDocument || element; return (doc.defaultView || doc.parentWindow || window); } var MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android/i; var SUPPORT_TOUCH = ('ontouchstart' in window); var SUPPORT_POINTER_EVENTS = prefixed(window, 'PointerEvent') !== undefined; var SUPPORT_ONLY_TOUCH = SUPPORT_TOUCH && MOBILE_REGEX.test(navigator.userAgent); var INPUT_TYPE_TOUCH = 'touch'; var INPUT_TYPE_PEN = 'pen'; var INPUT_TYPE_MOUSE = 'mouse'; var INPUT_TYPE_KINECT = 'kinect'; var COMPUTE_INTERVAL = 25; var INPUT_START = 1; var INPUT_MOVE = 2; var INPUT_END = 4; var INPUT_CANCEL = 8; var DIRECTION_NONE = 1; var DIRECTION_LEFT = 2; var DIRECTION_RIGHT = 4; var DIRECTION_UP = 8; var DIRECTION_DOWN = 16; var DIRECTION_HORIZONTAL = DIRECTION_LEFT | DIRECTION_RIGHT; var DIRECTION_VERTICAL = DIRECTION_UP | DIRECTION_DOWN; var DIRECTION_ALL = DIRECTION_HORIZONTAL | DIRECTION_VERTICAL; var PROPS_XY = ['x', 'y']; var PROPS_CLIENT_XY = ['clientX', 'clientY']; /** * create new input type manager * @param {Manager} manager * @param {Function} callback * @returns {Input} * @constructor */ function Input(manager, callback) { var self = this; this.manager = manager; this.callback = callback; this.element = manager.element; this.target = manager.options.inputTarget; // smaller wrapper around the handler, for the scope and the enabled state of the manager, // so when disabled the input events are completely bypassed. this.domHandler = function(ev) { if (boolOrFn(manager.options.enable, [manager])) { self.handler(ev); } }; this.init(); } Input.prototype = { /** * should handle the inputEvent data and trigger the callback * @virtual */ handler: function() { }, /** * bind the events */ init: function() { this.evEl && addEventListeners(this.element, this.evEl, this.domHandler); this.evTarget && addEventListeners(this.target, this.evTarget, this.domHandler); this.evWin && addEventListeners(getWindowForElement(this.element), this.evWin, this.domHandler); }, /** * unbind the events */ destroy: function() { this.evEl && removeEventListeners(this.element, this.evEl, this.domHandler); this.evTarget && removeEventListeners(this.target, this.evTarget, this.domHandler); this.evWin && removeEventListeners(getWindowForElement(this.element), this.evWin, this.domHandler); } }; /** * create new input type manager * called by the Manager constructor * @param {Hammer} manager * @returns {Input} */ function createInputInstance(manager) { var Type; var inputClass = manager.options.inputClass; if (inputClass) { Type = inputClass; } else if (SUPPORT_POINTER_EVENTS) { Type = PointerEventInput; } else if (SUPPORT_ONLY_TOUCH) { Type = TouchInput; } else if (!SUPPORT_TOUCH) { Type = MouseInput; } else { Type = TouchMouseInput; } return new (Type)(manager, inputHandler); } /** * handle input events * @param {Manager} manager * @param {String} eventType * @param {Object} input */ function inputHandler(manager, eventType, input) { var pointersLen = input.pointers.length; var changedPointersLen = input.changedPointers.length; var isFirst = (eventType & INPUT_START && (pointersLen - changedPointersLen === 0)); var isFinal = (eventType & (INPUT_END | INPUT_CANCEL) && (pointersLen - changedPointersLen === 0)); input.isFirst = !!isFirst; input.isFinal = !!isFinal; if (isFirst) { manager.session = {}; } // source event is the normalized value of the domEvents // like 'touchstart, mouseup, pointerdown' input.eventType = eventType; // compute scale, rotation etc computeInputData(manager, input); // emit secret event manager.emit('hammer.input', input); manager.recognize(input); manager.session.prevInput = input; } /** * extend the data with some usable properties like scale, rotate, velocity etc * @param {Object} manager * @param {Object} input */ function computeInputData(manager, input) { var session = manager.session; var pointers = input.pointers; var pointersLength = pointers.length; // store the first input to calculate the distance and direction if (!session.firstInput) { session.firstInput = simpleCloneInputData(input); } // to compute scale and rotation we need to store the multiple touches if (pointersLength > 1 && !session.firstMultiple) { session.firstMultiple = simpleCloneInputData(input); } else if (pointersLength === 1) { session.firstMultiple = false; } var firstInput = session.firstInput; var firstMultiple = session.firstMultiple; var offsetCenter = firstMultiple ? firstMultiple.center : firstInput.center; var center = input.center = getCenter(pointers); input.timeStamp = now(); input.deltaTime = input.timeStamp - firstInput.timeStamp; input.angle = getAngle(offsetCenter, center); input.distance = getDistance(offsetCenter, center); computeDeltaXY(session, input); input.offsetDirection = getDirection(input.deltaX, input.deltaY); var overallVelocity = getVelocity(input.deltaTime, input.deltaX, input.deltaY); input.overallVelocityX = overallVelocity.x; input.overallVelocityY = overallVelocity.y; input.overallVelocity = (abs(overallVelocity.x) > abs(overallVelocity.y)) ? overallVelocity.x : overallVelocity.y; input.scale = firstMultiple ? getScale(firstMultiple.pointers, pointers) : 1; input.rotation = firstMultiple ? getRotation(firstMultiple.pointers, pointers) : 0; input.maxPointers = !session.prevInput ? input.pointers.length : ((input.pointers.length > session.prevInput.maxPointers) ? input.pointers.length : session.prevInput.maxPointers); computeIntervalInputData(session, input); // find the correct target var target = manager.element; if (hasParent(input.srcEvent.target, target)) { target = input.srcEvent.target; } input.target = target; } function computeDeltaXY(session, input) { var center = input.center; var offset = session.offsetDelta || {}; var prevDelta = session.prevDelta || {}; var prevInput = session.prevInput || {}; if (input.eventType === INPUT_START || prevInput.eventType === INPUT_END) { prevDelta = session.prevDelta = { x: prevInput.deltaX || 0, y: prevInput.deltaY || 0 }; offset = session.offsetDelta = { x: center.x, y: center.y }; } input.deltaX = prevDelta.x + (center.x - offset.x); input.deltaY = prevDelta.y + (center.y - offset.y); } /** * velocity is calculated every x ms * @param {Object} session * @param {Object} input */ function computeIntervalInputData(session, input) { var last = session.lastInterval || input, deltaTime = input.timeStamp - last.timeStamp, velocity, velocityX, velocityY, direction; if (input.eventType != INPUT_CANCEL && (deltaTime > COMPUTE_INTERVAL || last.velocity === undefined)) { var deltaX = input.deltaX - last.deltaX; var deltaY = input.deltaY - last.deltaY; var v = getVelocity(deltaTime, deltaX, deltaY); velocityX = v.x; velocityY = v.y; velocity = (abs(v.x) > abs(v.y)) ? v.x : v.y; direction = getDirection(deltaX, deltaY); session.lastInterval = input; } else { // use latest velocity info if it doesn't overtake a minimum period velocity = last.velocity; velocityX = last.velocityX; velocityY = last.velocityY; direction = last.direction; } input.velocity = velocity; input.velocityX = velocityX; input.velocityY = velocityY; input.direction = direction; } /** * create a simple clone from the input used for storage of firstInput and firstMultiple * @param {Object} input * @returns {Object} clonedInputData */ function simpleCloneInputData(input) { // make a simple copy of the pointers because we will get a reference if we don't // we only need clientXY for the calculations var pointers = []; var i = 0; while (i < input.pointers.length) { pointers[i] = { clientX: round(input.pointers[i].clientX), clientY: round(input.pointers[i].clientY) }; i++; } return { timeStamp: now(), pointers: pointers, center: getCenter(pointers), deltaX: input.deltaX, deltaY: input.deltaY }; } /** * get the center of all the pointers * @param {Array} pointers * @return {Object} center contains `x` and `y` properties */ function getCenter(pointers) { var pointersLength = pointers.length; // no need to loop when only one touch if (pointersLength === 1) { return { x: round(pointers[0].clientX), y: round(pointers[0].clientY) }; } var x = 0, y = 0, i = 0; while (i < pointersLength) { x += pointers[i].clientX; y += pointers[i].clientY; i++; } return { x: round(x / pointersLength), y: round(y / pointersLength) }; } /** * calculate the velocity between two points. unit is in px per ms. * @param {Number} deltaTime * @param {Number} x * @param {Number} y * @return {Object} velocity `x` and `y` */ function getVelocity(deltaTime, x, y) { return { x: x / deltaTime || 0, y: y / deltaTime || 0 }; } /** * get the direction between two points * @param {Number} x * @param {Number} y * @return {Number} direction */ function getDirection(x, y) { if (x === y) { return DIRECTION_NONE; } if (abs(x) >= abs(y)) { return x < 0 ? DIRECTION_LEFT : DIRECTION_RIGHT; } return y < 0 ? DIRECTION_UP : DIRECTION_DOWN; } /** * calculate the absolute distance between two points * @param {Object} p1 {x, y} * @param {Object} p2 {x, y} * @param {Array} [props] containing x and y keys * @return {Number} distance */ function getDistance(p1, p2, props) { if (!props) { props = PROPS_XY; } var x = p2[props[0]] - p1[props[0]], y = p2[props[1]] - p1[props[1]]; return Math.sqrt((x * x) + (y * y)); } /** * calculate the angle between two coordinates * @param {Object} p1 * @param {Object} p2 * @param {Array} [props] containing x and y keys * @return {Number} angle */ function getAngle(p1, p2, props) { if (!props) { props = PROPS_XY; } var x = p2[props[0]] - p1[props[0]], y = p2[props[1]] - p1[props[1]]; return Math.atan2(y, x) * 180 / Math.PI; } /** * calculate the rotation degrees between two pointersets * @param {Array} start array of pointers * @param {Array} end array of pointers * @return {Number} rotation */ function getRotation(start, end) { return getAngle(end[1], end[0], PROPS_CLIENT_XY) + getAngle(start[1], start[0], PROPS_CLIENT_XY); } /** * calculate the scale factor between two pointersets * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out * @param {Array} start array of pointers * @param {Array} end array of pointers * @return {Number} scale */ function getScale(start, end) { return getDistance(end[0], end[1], PROPS_CLIENT_XY) / getDistance(start[0], start[1], PROPS_CLIENT_XY); } var MOUSE_INPUT_MAP = { mousedown: INPUT_START, mousemove: INPUT_MOVE, mouseup: INPUT_END }; var MOUSE_ELEMENT_EVENTS = 'mousedown'; var MOUSE_WINDOW_EVENTS = 'mousemove mouseup'; /** * Mouse events input * @constructor * @extends Input */ function MouseInput() { this.evEl = MOUSE_ELEMENT_EVENTS; this.evWin = MOUSE_WINDOW_EVENTS; this.pressed = false; // mousedown state Input.apply(this, arguments); } inherit(MouseInput, Input, { /** * handle mouse events * @param {Object} ev */ handler: function MEhandler(ev) { var eventType = MOUSE_INPUT_MAP[ev.type]; // on start we want to have the left mouse button down if (eventType & INPUT_START && ev.button === 0) { this.pressed = true; } if (eventType & INPUT_MOVE && ev.which !== 1) { eventType = INPUT_END; } // mouse must be down if (!this.pressed) { return; } if (eventType & INPUT_END) { this.pressed = false; } this.callback(this.manager, eventType, { pointers: [ev], changedPointers: [ev], pointerType: INPUT_TYPE_MOUSE, srcEvent: ev }); } }); var POINTER_INPUT_MAP = { pointerdown: INPUT_START, pointermove: INPUT_MOVE, pointerup: INPUT_END, pointercancel: INPUT_CANCEL, pointerout: INPUT_CANCEL }; // in IE10 the pointer types is defined as an enum var IE10_POINTER_TYPE_ENUM = { 2: INPUT_TYPE_TOUCH, 3: INPUT_TYPE_PEN, 4: INPUT_TYPE_MOUSE, 5: INPUT_TYPE_KINECT // see https://twitter.com/jacobrossi/status/480596438489890816 }; var POINTER_ELEMENT_EVENTS = 'pointerdown'; var POINTER_WINDOW_EVENTS = 'pointermove pointerup pointercancel'; // IE10 has prefixed support, and case-sensitive if (window.MSPointerEvent && !window.PointerEvent) { POINTER_ELEMENT_EVENTS = 'MSPointerDown'; POINTER_WINDOW_EVENTS = 'MSPointerMove MSPointerUp MSPointerCancel'; } /** * Pointer events input * @constructor * @extends Input */ function PointerEventInput() { this.evEl = POINTER_ELEMENT_EVENTS; this.evWin = POINTER_WINDOW_EVENTS; Input.apply(this, arguments); this.store = (this.manager.session.pointerEvents = []); } inherit(PointerEventInput, Input, { /** * handle mouse events * @param {Object} ev */ handler: function PEhandler(ev) { var store = this.store; var removePointer = false; var eventTypeNormalized = ev.type.toLowerCase().replace('ms', ''); var eventType = POINTER_INPUT_MAP[eventTypeNormalized]; var pointerType = IE10_POINTER_TYPE_ENUM[ev.pointerType] || ev.pointerType; var isTouch = (pointerType == INPUT_TYPE_TOUCH); // get index of the event in the store var storeIndex = inArray(store, ev.pointerId, 'pointerId'); // start and mouse must be down if (eventType & INPUT_START && (ev.button === 0 || isTouch)) { if (storeIndex < 0) { store.push(ev); storeIndex = store.length - 1; } } else if (eventType & (INPUT_END | INPUT_CANCEL)) { removePointer = true; } // it not found, so the pointer hasn't been down (so it's probably a hover) if (storeIndex < 0) { return; } // update the event in the store store[storeIndex] = ev; this.callback(this.manager, eventType, { pointers: store, changedPointers: [ev], pointerType: pointerType, srcEvent: ev }); if (removePointer) { // remove from the store store.splice(storeIndex, 1); } } }); var SINGLE_TOUCH_INPUT_MAP = { touchstart: INPUT_START, touchmove: INPUT_MOVE, touchend: INPUT_END, touchcancel: INPUT_CANCEL }; var SINGLE_TOUCH_TARGET_EVENTS = 'touchstart'; var SINGLE_TOUCH_WINDOW_EVENTS = 'touchstart touchmove touchend touchcancel'; /** * Touch events input * @constructor * @extends Input */ function SingleTouchInput() { this.evTarget = SINGLE_TOUCH_TARGET_EVENTS; this.evWin = SINGLE_TOUCH_WINDOW_EVENTS; this.started = false; Input.apply(this, arguments); } inherit(SingleTouchInput, Input, { handler: function TEhandler(ev) { var type = SINGLE_TOUCH_INPUT_MAP[ev.type]; // should we handle the touch events? if (type === INPUT_START) { this.started = true; } if (!this.started) { return; } var touches = normalizeSingleTouches.call(this, ev, type); // when done, reset the started state if (type & (INPUT_END | INPUT_CANCEL) && touches[0].length - touches[1].length === 0) { this.started = false; } this.callback(this.manager, type, { pointers: touches[0], changedPointers: touches[1], pointerType: INPUT_TYPE_TOUCH, srcEvent: ev }); } }); /** * @this {TouchInput} * @param {Object} ev * @param {Number} type flag * @returns {undefined|Array} [all, changed] */ function normalizeSingleTouches(ev, type) { var all = toArray(ev.touches); var changed = toArray(ev.changedTouches); if (type & (INPUT_END | INPUT_CANCEL)) { all = uniqueArray(all.concat(changed), 'identifier', true); } return [all, changed]; } var TOUCH_INPUT_MAP = { touchstart: INPUT_START, touchmove: INPUT_MOVE, touchend: INPUT_END, touchcancel: INPUT_CANCEL }; var TOUCH_TARGET_EVENTS = 'touchstart touchmove touchend touchcancel'; /** * Multi-user touch events input * @constructor * @extends Input */ function TouchInput() { this.evTarget = TOUCH_TARGET_EVENTS; this.targetIds = {}; Input.apply(this, arguments); } inherit(TouchInput, Input, { handler: function MTEhandler(ev) { var type = TOUCH_INPUT_MAP[ev.type]; var touches = getTouches.call(this, ev, type); if (!touches) { return; } this.callback(this.manager, type, { pointers: touches[0], changedPointers: touches[1], pointerType: INPUT_TYPE_TOUCH, srcEvent: ev }); } }); /** * @this {TouchInput} * @param {Object} ev * @param {Number} type flag * @returns {undefined|Array} [all, changed] */ function getTouches(ev, type) { var allTouches = toArray(ev.touches); var targetIds = this.targetIds; // when there is only one touch, the process can be simplified if (type & (INPUT_START | INPUT_MOVE) && allTouches.length === 1) { targetIds[allTouches[0].identifier] = true; return [allTouches, allTouches]; } var i, targetTouches, changedTouches = toArray(ev.changedTouches), changedTargetTouches = [], target = this.target; // get target touches from touches targetTouches = allTouches.filter(function(touch) { return hasParent(touch.target, target); }); // collect touches if (type === INPUT_START) { i = 0; while (i < targetTouches.length) { targetIds[targetTouches[i].identifier] = true; i++; } } // filter changed touches to only contain touches that exist in the collected target ids i = 0; while (i < changedTouches.length) { if (targetIds[changedTouches[i].identifier]) { changedTargetTouches.push(changedTouches[i]); } // cleanup removed touches if (type & (INPUT_END | INPUT_CANCEL)) { delete targetIds[changedTouches[i].identifier]; } i++; } if (!changedTargetTouches.length) { return; } return [ // merge targetTouches with changedTargetTouches so it contains ALL touches, including 'end' and 'cancel' uniqueArray(targetTouches.concat(changedTargetTouches), 'identifier', true), changedTargetTouches ]; } /** * Combined touch and mouse input * * Touch has a higher priority then mouse, and while touching no mouse events are allowed. * This because touch devices also emit mouse events while doing a touch. * * @constructor * @extends Input */ var DEDUP_TIMEOUT = 2500; var DEDUP_DISTANCE = 25; function TouchMouseInput() { Input.apply(this, arguments); var handler = bindFn(this.handler, this); this.touch = new TouchInput(this.manager, handler); this.mouse = new MouseInput(this.manager, handler); this.primaryTouch = null; this.lastTouches = []; } inherit(TouchMouseInput, Input, { /** * handle mouse and touch events * @param {Hammer} manager * @param {String} inputEvent * @param {Object} inputData */ handler: function TMEhandler(manager, inputEvent, inputData) { var isTouch = (inputData.pointerType == INPUT_TYPE_TOUCH), isMouse = (inputData.pointerType == INPUT_TYPE_MOUSE); if (isMouse && inputData.sourceCapabilities && inputData.sourceCapabilities.firesTouchEvents) { return; } // when we're in a touch event, record touches to de-dupe synthetic mouse event if (isTouch) { recordTouches.call(this, inputEvent, inputData); } else if (isMouse && isSyntheticEvent.call(this, inputData)) { return; } this.callback(manager, inputEvent, inputData); }, /** * remove the event listeners */ destroy: function destroy() { this.touch.destroy(); this.mouse.destroy(); } }); function recordTouches(eventType, eventData) { if (eventType & INPUT_START) { this.primaryTouch = eventData.changedPointers[0].identifier; setLastTouch.call(this, eventData); } else if (eventType & (INPUT_END | INPUT_CANCEL)) { setLastTouch.call(this, eventData); } } function setLastTouch(eventData) { var touch = eventData.changedPointers[0]; if (touch.identifier === this.primaryTouch) { var lastTouch = {x: touch.clientX, y: touch.clientY}; this.lastTouches.push(lastTouch); var lts = this.lastTouches; var removeLastTouch = function() { var i = lts.indexOf(lastTouch); if (i > -1) { lts.splice(i, 1); } }; setTimeout(removeLastTouch, DEDUP_TIMEOUT); } } function isSyntheticEvent(eventData) { var x = eventData.srcEvent.clientX, y = eventData.srcEvent.clientY; for (var i = 0; i < this.lastTouches.length; i++) { var t = this.lastTouches[i]; var dx = Math.abs(x - t.x), dy = Math.abs(y - t.y); if (dx <= DEDUP_DISTANCE && dy <= DEDUP_DISTANCE) { return true; } } return false; } var PREFIXED_TOUCH_ACTION = prefixed(TEST_ELEMENT.style, 'touchAction'); var NATIVE_TOUCH_ACTION = PREFIXED_TOUCH_ACTION !== undefined; // magical touchAction value var TOUCH_ACTION_COMPUTE = 'compute'; var TOUCH_ACTION_AUTO = 'auto'; var TOUCH_ACTION_MANIPULATION = 'manipulation'; // not implemented var TOUCH_ACTION_NONE = 'none'; var TOUCH_ACTION_PAN_X = 'pan-x'; var TOUCH_ACTION_PAN_Y = 'pan-y'; var TOUCH_ACTION_MAP = getTouchActionProps(); /** * Touch Action * sets the touchAction property or uses the js alternative * @param {Manager} manager * @param {String} value * @constructor */ function TouchAction(manager, value) { this.manager = manager; this.set(value); } TouchAction.prototype = { /** * set the touchAction value on the element or enable the polyfill * @param {String} value */ set: function(value) { // find out the touch-action by the event handlers if (value == TOUCH_ACTION_COMPUTE) { value = this.compute(); } if (NATIVE_TOUCH_ACTION && this.manager.element.style && TOUCH_ACTION_MAP[value]) { this.manager.element.style[PREFIXED_TOUCH_ACTION] = value; } this.actions = value.toLowerCase().trim(); }, /** * just re-set the touchAction value */ update: function() { this.set(this.manager.options.touchAction); }, /** * compute the value for the touchAction property based on the recognizer's settings * @returns {String} value */ compute: function() { var actions = []; each(this.manager.recognizers, function(recognizer) { if (boolOrFn(recognizer.options.enable, [recognizer])) { actions = actions.concat(recognizer.getTouchAction()); } }); return cleanTouchActions(actions.join(' ')); }, /** * this method is called on each input cycle and provides the preventing of the browser behavior * @param {Object} input */ preventDefaults: function(input) { var srcEvent = input.srcEvent; var direction = input.offsetDirection; // if the touch action did prevented once this session if (this.manager.session.prevented) { srcEvent.preventDefault(); return; } var actions = this.actions; var hasNone = inStr(actions, TOUCH_ACTION_NONE) && !TOUCH_ACTION_MAP[TOUCH_ACTION_NONE]; var hasPanY = inStr(actions, TOUCH_ACTION_PAN_Y) && !TOUCH_ACTION_MAP[TOUCH_ACTION_PAN_Y]; var hasPanX = inStr(actions, TOUCH_ACTION_PAN_X) && !TOUCH_ACTION_MAP[TOUCH_ACTION_PAN_X]; if (hasNone) { //do not prevent defaults if this is a tap gesture var isTapPointer = input.pointers.length === 1; var isTapMovement = input.distance < 2; var isTapTouchTime = input.deltaTime < 250; if (isTapPointer && isTapMovement && isTapTouchTime) { return; } } if (hasPanX && hasPanY) { // `pan-x pan-y` means browser handles all scrolling/panning, do not prevent return; } if (hasNone || (hasPanY && direction & DIRECTION_HORIZONTAL) || (hasPanX && direction & DIRECTION_VERTICAL)) { return this.preventSrc(srcEvent); } }, /** * call preventDefault to prevent the browser's default behavior (scrolling in most cases) * @param {Object} srcEvent */ preventSrc: function(srcEvent) { this.manager.session.prevented = true; srcEvent.preventDefault(); } }; /** * when the touchActions are collected they are not a valid value, so we need to clean things up. * * @param {String} actions * @returns {*} */ function cleanTouchActions(actions) { // none if (inStr(actions, TOUCH_ACTION_NONE)) { return TOUCH_ACTION_NONE; } var hasPanX = inStr(actions, TOUCH_ACTION_PAN_X); var hasPanY = inStr(actions, TOUCH_ACTION_PAN_Y); // if both pan-x and pan-y are set (different recognizers // for different directions, e.g. horizontal pan but vertical swipe?) // we need none (as otherwise with pan-x pan-y combined none of these // recognizers will work, since the browser would handle all panning if (hasPanX && hasPanY) { return TOUCH_ACTION_NONE; } // pan-x OR pan-y if (hasPanX || hasPanY) { return hasPanX ? TOUCH_ACTION_PAN_X : TOUCH_ACTION_PAN_Y; } // manipulation if (inStr(actions, TOUCH_ACTION_MANIPULATION)) { return TOUCH_ACTION_MANIPULATION; } return TOUCH_ACTION_AUTO; } function getTouchActionProps() { if (!NATIVE_TOUCH_ACTION) { return false; } var touchMap = {}; var cssSupports = window.CSS && window.CSS.supports; ['auto', 'manipulation', 'pan-y', 'pan-x', 'pan-x pan-y', 'none'].forEach(function(val) { // If css.supports is not supported but there is native touch-action assume it supports // all values. This is the case for IE 10 and 11. touchMap[val] = cssSupports ? window.CSS.supports('touch-action', val) : true; }); return touchMap; } /** * Recognizer flow explained; * * All recognizers have the initial state of POSSIBLE when a input session starts. * The definition of a input session is from the first input until the last input, with all it's movement in it. * * Example session for mouse-input: mousedown -> mousemove -> mouseup * * On each recognizing cycle (see Manager.recognize) the .recognize() method is executed * which determines with state it should be. * * If the recognizer has the state FAILED, CANCELLED or RECOGNIZED (equals ENDED), it is reset to * POSSIBLE to give it another change on the next cycle. * * Possible * | * +-----+---------------+ * | | * +-----+-----+ | * | | | * Failed Cancelled | * +-------+------+ * | | * Recognized Began * | * Changed * | * Ended/Recognized */ var STATE_POSSIBLE = 1; var STATE_BEGAN = 2; var STATE_CHANGED = 4; var STATE_ENDED = 8; var STATE_RECOGNIZED = STATE_ENDED; var STATE_CANCELLED = 16; var STATE_FAILED = 32; /** * Recognizer * Every recognizer needs to extend from this class. * @constructor * @param {Object} options */ function Recognizer(options) { this.options = assign({}, this.defaults, options || {}); this.id = uniqueId(); this.manager = null; // default is enable true this.options.enable = ifUndefined(this.options.enable, true); this.state = STATE_POSSIBLE; this.simultaneous = {}; this.requireFail = []; } Recognizer.prototype = { /** * @virtual * @type {Object} */ defaults: {}, /** * set options * @param {Object} options * @return {Recognizer} */ set: function(options) { assign(this.options, options); // also update the touchAction, in case something changed about the directions/enabled state this.manager && this.manager.touchAction.update(); return this; }, /** * recognize simultaneous with an other recognizer. * @param {Recognizer} otherRecognizer * @returns {Recognizer} this */ recognizeWith: function(otherRecognizer) { if (invokeArrayArg(otherRecognizer, 'recognizeWith', this)) { return this; } var simultaneous = this.simultaneous; otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this); if (!simultaneous[otherRecognizer.id]) { simultaneous[otherRecognizer.id] = otherRecognizer; otherRecognizer.recognizeWith(this); } return this; }, /** * drop the simultaneous link. it doesnt remove the link on the other recognizer. * @param {Recognizer} otherRecognizer * @returns {Recognizer} this */ dropRecognizeWith: function(otherRecognizer) { if (invokeArrayArg(otherRecognizer, 'dropRecognizeWith', this)) { return this; } otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this); delete this.simultaneous[otherRecognizer.id]; return this; }, /** * recognizer can only run when an other is failing * @param {Recognizer} otherRecognizer * @returns {Recognizer} this */ requireFailure: function(otherRecognizer) { if (invokeArrayArg(otherRecognizer, 'requireFailure', this)) { return this; } var requireFail = this.requireFail; otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this); if (inArray(requireFail, otherRecognizer) === -1) { requireFail.push(otherRecognizer); otherRecognizer.requireFailure(this); } return this; }, /** * drop the requireFailure link. it does not remove the link on the other recognizer. * @param {Recognizer} otherRecognizer * @returns {Recognizer} this */ dropRequireFailure: function(otherRecognizer) { if (invokeArrayArg(otherRecognizer, 'dropRequireFailure', this)) { return this; } otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this); var index = inArray(this.requireFail, otherRecognizer); if (index > -1) { this.requireFail.splice(index, 1); } return this; }, /** * has require failures boolean * @returns {boolean} */ hasRequireFailures: function() { return this.requireFail.length > 0; }, /** * if the recognizer can recognize simultaneous with an other recognizer * @param {Recognizer} otherRecognizer * @returns {Boolean} */ canRecognizeWith: function(otherRecognizer) { return !!this.simultaneous[otherRecognizer.id]; }, /** * You should use `tryEmit` instead of `emit` directly to check * that all the needed recognizers has failed before emitting. * @param {Object} input */ emit: function(input) { var self = this; var state = this.state; function emit(event) { self.manager.emit(event, input); } // 'panstart' and 'panmove' if (state < STATE_ENDED) { emit(self.options.event + stateStr(state)); } emit(self.options.event); // simple 'eventName' events if (input.additionalEvent) { // additional event(panleft, panright, pinchin, pinchout...) emit(input.additionalEvent); } // panend and pancancel if (state >= STATE_ENDED) { emit(self.options.event + stateStr(state)); } }, /** * Check that all the require failure recognizers has failed, * if true, it emits a gesture event, * otherwise, setup the state to FAILED. * @param {Object} input */ tryEmit: function(input) { if (this.canEmit()) { return this.emit(input); } // it's failing anyway this.state = STATE_FAILED; }, /** * can we emit? * @returns {boolean} */ canEmit: function() { var i = 0; while (i < this.requireFail.length) { if (!(this.requireFail[i].state & (STATE_FAILED | STATE_POSSIBLE))) { return false; } i++; } return true; }, /** * update the recognizer * @param {Object} inputData */ recognize: function(inputData) { // make a new copy of the inputData // so we can change the inputData without messing up the other recognizers var inputDataClone = assign({}, inputData); // is is enabled and allow recognizing? if (!boolOrFn(this.options.enable, [this, inputDataClone])) { this.reset(); this.state = STATE_FAILED; return; } // reset when we've reached the end if (this.state & (STATE_RECOGNIZED | STATE_CANCELLED | STATE_FAILED)) { this.state = STATE_POSSIBLE; } this.state = this.process(inputDataClone); // the recognizer has recognized a gesture // so trigger an event if (this.state & (STATE_BEGAN | STATE_CHANGED | STATE_ENDED | STATE_CANCELLED)) { this.tryEmit(inputDataClone); } }, /** * return the state of the recognizer * the actual recognizing happens in this method * @virtual * @param {Object} inputData * @returns {Const} STATE */ process: function(inputData) { }, // jshint ignore:line /** * return the preferred touch-action * @virtual * @returns {Array} */ getTouchAction: function() { }, /** * called when the gesture isn't allowed to recognize * like when another is being recognized or it is disabled * @virtual */ reset: function() { } }; /** * get a usable string, used as event postfix * @param {Const} state * @returns {String} state */ function stateStr(state) { if (state & STATE_CANCELLED) { return 'cancel'; } else if (state & STATE_ENDED) { return 'end'; } else if (state & STATE_CHANGED) { return 'move'; } else if (state & STATE_BEGAN) { return 'start'; } return ''; } /** * direction cons to string * @param {Const} direction * @returns {String} */ function directionStr(direction) { if (direction == DIRECTION_DOWN) { return 'down'; } else if (direction == DIRECTION_UP) { return 'up'; } else if (direction == DIRECTION_LEFT) { return 'left'; } else if (direction == DIRECTION_RIGHT) { return 'right'; } return ''; } /** * get a recognizer by name if it is bound to a manager * @param {Recognizer|String} otherRecognizer * @param {Recognizer} recognizer * @returns {Recognizer} */ function getRecognizerByNameIfManager(otherRecognizer, recognizer) { var manager = recognizer.manager; if (manager) { return manager.get(otherRecognizer); } return otherRecognizer; } /** * This recognizer is just used as a base for the simple attribute recognizers. * @constructor * @extends Recognizer */ function AttrRecognizer() { Recognizer.apply(this, arguments); } inherit(AttrRecognizer, Recognizer, { /** * @namespace * @memberof AttrRecognizer */ defaults: { /** * @type {Number} * @default 1 */ pointers: 1 }, /** * Used to check if it the recognizer receives valid input, like input.distance > 10. * @memberof AttrRecognizer * @param {Object} input * @returns {Boolean} recognized */ attrTest: function(input) { var optionPointers = this.options.pointers; return optionPointers === 0 || input.pointers.length === optionPointers; }, /** * Process the input and return the state for the recognizer * @memberof AttrRecognizer * @param {Object} input * @returns {*} State */ process: function(input) { var state = this.state; var eventType = input.eventType; var isRecognized = state & (STATE_BEGAN | STATE_CHANGED); var isValid = this.attrTest(input); // on cancel input and we've recognized before, return STATE_CANCELLED if (isRecognized && (eventType & INPUT_CANCEL || !isValid)) { return state | STATE_CANCELLED; } else if (isRecognized || isValid) { if (eventType & INPUT_END) { return state | STATE_ENDED; } else if (!(state & STATE_BEGAN)) { return STATE_BEGAN; } return state | STATE_CHANGED; } return STATE_FAILED; } }); /** * Pan * Recognized when the pointer is down and moved in the allowed direction. * @constructor * @extends AttrRecognizer */ function PanRecognizer() { AttrRecognizer.apply(this, arguments); this.pX = null; this.pY = null; } inherit(PanRecognizer, AttrRecognizer, { /** * @namespace * @memberof PanRecognizer */ defaults: { event: 'pan', threshold: 10, pointers: 1, direction: DIRECTION_ALL }, getTouchAction: function() { var direction = this.options.direction; var actions = []; if (direction & DIRECTION_HORIZONTAL) { actions.push(TOUCH_ACTION_PAN_Y); } if (direction & DIRECTION_VERTICAL) { actions.push(TOUCH_ACTION_PAN_X); } return actions; }, directionTest: function(input) { var options = this.options; var hasMoved = true; var distance = input.distance; var direction = input.direction; var x = input.deltaX; var y = input.deltaY; // lock to axis? if (!(direction & options.direction)) { if (options.direction & DIRECTION_HORIZONTAL) { direction = (x === 0) ? DIRECTION_NONE : (x < 0) ? DIRECTION_LEFT : DIRECTION_RIGHT; hasMoved = x != this.pX; distance = Math.abs(input.deltaX); } else { direction = (y === 0) ? DIRECTION_NONE : (y < 0) ? DIRECTION_UP : DIRECTION_DOWN; hasMoved = y != this.pY; distance = Math.abs(input.deltaY); } } input.direction = direction; return hasMoved && distance > options.threshold && direction & options.direction; }, attrTest: function(input) { return AttrRecognizer.prototype.attrTest.call(this, input) && (this.state & STATE_BEGAN || (!(this.state & STATE_BEGAN) && this.directionTest(input))); }, emit: function(input) { this.pX = input.deltaX; this.pY = input.deltaY; var direction = directionStr(input.direction); if (direction) { input.additionalEvent = this.options.event + direction; } this._super.emit.call(this, input); } }); /** * Pinch * Recognized when two or more pointers are moving toward (zoom-in) or away from each other (zoom-out). * @constructor * @extends AttrRecognizer */ function PinchRecognizer() { AttrRecognizer.apply(this, arguments); } inherit(PinchRecognizer, AttrRecognizer, { /** * @namespace * @memberof PinchRecognizer */ defaults: { event: 'pinch', threshold: 0, pointers: 2 }, getTouchAction: function() { return [TOUCH_ACTION_NONE]; }, attrTest: function(input) { return this._super.attrTest.call(this, input) && (Math.abs(input.scale - 1) > this.options.threshold || this.state & STATE_BEGAN); }, emit: function(input) { if (input.scale !== 1) { var inOut = input.scale < 1 ? 'in' : 'out'; input.additionalEvent = this.options.event + inOut; } this._super.emit.call(this, input); } }); /** * Press * Recognized when the pointer is down for x ms without any movement. * @constructor * @extends Recognizer */ function PressRecognizer() { Recognizer.apply(this, arguments); this._timer = null; this._input = null; } inherit(PressRecognizer, Recognizer, { /** * @namespace * @memberof PressRecognizer */ defaults: { event: 'press', pointers: 1, time: 251, // minimal time of the pointer to be pressed threshold: 9 // a minimal movement is ok, but keep it low }, getTouchAction: function() { return [TOUCH_ACTION_AUTO]; }, process: function(input) { var options = this.options; var validPointers = input.pointers.length === options.pointers; var validMovement = input.distance < options.threshold; var validTime = input.deltaTime > options.time; this._input = input; // we only allow little movement // and we've reached an end event, so a tap is possible if (!validMovement || !validPointers || (input.eventType & (INPUT_END | INPUT_CANCEL) && !validTime)) { this.reset(); } else if (input.eventType & INPUT_START) { this.reset(); this._timer = setTimeoutContext(function() { this.state = STATE_RECOGNIZED; this.tryEmit(); }, options.time, this); } else if (input.eventType & INPUT_END) { return STATE_RECOGNIZED; } return STATE_FAILED; }, reset: function() { clearTimeout(this._timer); }, emit: function(input) { if (this.state !== STATE_RECOGNIZED) { return; } if (input && (input.eventType & INPUT_END)) { this.manager.emit(this.options.event + 'up', input); } else { this._input.timeStamp = now(); this.manager.emit(this.options.event, this._input); } } }); /** * Rotate * Recognized when two or more pointer are moving in a circular motion. * @constructor * @extends AttrRecognizer */ function RotateRecognizer() { AttrRecognizer.apply(this, arguments); } inherit(RotateRecognizer, AttrRecognizer, { /** * @namespace * @memberof RotateRecognizer */ defaults: { event: 'rotate', threshold: 0, pointers: 2 }, getTouchAction: function() { return [TOUCH_ACTION_NONE]; }, attrTest: function(input) { return this._super.attrTest.call(this, input) && (Math.abs(input.rotation) > this.options.threshold || this.state & STATE_BEGAN); } }); /** * Swipe * Recognized when the pointer is moving fast (velocity), with enough distance in the allowed direction. * @constructor * @extends AttrRecognizer */ function SwipeRecognizer() { AttrRecognizer.apply(this, arguments); } inherit(SwipeRecognizer, AttrRecognizer, { /** * @namespace * @memberof SwipeRecognizer */ defaults: { event: 'swipe', threshold: 10, velocity: 0.3, direction: DIRECTION_HORIZONTAL | DIRECTION_VERTICAL, pointers: 1 }, getTouchAction: function() { return PanRecognizer.prototype.getTouchAction.call(this); }, attrTest: function(input) { var direction = this.options.direction; var velocity; if (direction & (DIRECTION_HORIZONTAL | DIRECTION_VERTICAL)) { velocity = input.overallVelocity; } else if (direction & DIRECTION_HORIZONTAL) { velocity = input.overallVelocityX; } else if (direction & DIRECTION_VERTICAL) { velocity = input.overallVelocityY; } return this._super.attrTest.call(this, input) && direction & input.offsetDirection && input.distance > this.options.threshold && input.maxPointers == this.options.pointers && abs(velocity) > this.options.velocity && input.eventType & INPUT_END; }, emit: function(input) { var direction = directionStr(input.offsetDirection); if (direction) { this.manager.emit(this.options.event + direction, input); } this.manager.emit(this.options.event, input); } }); /** * A tap is ecognized when the pointer is doing a small tap/click. Multiple taps are recognized if they occur * between the given interval and position. The delay option can be used to recognize multi-taps without firing * a single tap. * * The eventData from the emitted event contains the property `tapCount`, which contains the amount of * multi-taps being recognized. * @constructor * @extends Recognizer */ function TapRecognizer() { Recognizer.apply(this, arguments); // previous time and center, // used for tap counting this.pTime = false; this.pCenter = false; this._timer = null; this._input = null; this.count = 0; } inherit(TapRecognizer, Recognizer, { /** * @namespace * @memberof PinchRecognizer */ defaults: { event: 'tap', pointers: 1, taps: 1, interval: 300, // max time between the multi-tap taps time: 250, // max time of the pointer to be down (like finger on the screen) threshold: 9, // a minimal movement is ok, but keep it low posThreshold: 10 // a multi-tap can be a bit off the initial position }, getTouchAction: function() { return [TOUCH_ACTION_MANIPULATION]; }, process: function(input) { var options = this.options; var validPointers = input.pointers.length === options.pointers; var validMovement = input.distance < options.threshold; var validTouchTime = input.deltaTime < options.time; this.reset(); if ((input.eventType & INPUT_START) && (this.count === 0)) { return this.failTimeout(); } // we only allow little movement // and we've reached an end event, so a tap is possible if (validMovement && validTouchTime && validPointers) { if (input.eventType != INPUT_END) { return this.failTimeout(); } var validInterval = this.pTime ? (input.timeStamp - this.pTime < options.interval) : true; var validMultiTap = !this.pCenter || getDistance(this.pCenter, input.center) < options.posThreshold; this.pTime = input.timeStamp; this.pCenter = input.center; if (!validMultiTap || !validInterval) { this.count = 1; } else { this.count += 1; } this._input = input; // if tap count matches we have recognized it, // else it has began recognizing... var tapCount = this.count % options.taps; if (tapCount === 0) { // no failing requirements, immediately trigger the tap event // or wait as long as the multitap interval to trigger if (!this.hasRequireFailures()) { return STATE_RECOGNIZED; } else { this._timer = setTimeoutContext(function() { this.state = STATE_RECOGNIZED; this.tryEmit(); }, options.interval, this); return STATE_BEGAN; } } } return STATE_FAILED; }, failTimeout: function() { this._timer = setTimeoutContext(function() { this.state = STATE_FAILED; }, this.options.interval, this); return STATE_FAILED; }, reset: function() { clearTimeout(this._timer); }, emit: function() { if (this.state == STATE_RECOGNIZED) { this._input.tapCount = this.count; this.manager.emit(this.options.event, this._input); } } }); /** * Simple way to create a manager with a default set of recognizers. * @param {HTMLElement} element * @param {Object} [options] * @constructor */ function Hammer(element, options) { options = options || {}; options.recognizers = ifUndefined(options.recognizers, Hammer.defaults.preset); return new Manager(element, options); } /** * @const {string} */ Hammer.VERSION = '2.0.7'; /** * default settings * @namespace */ Hammer.defaults = { /** * set if DOM events are being triggered. * But this is slower and unused by simple implementations, so disabled by default. * @type {Boolean} * @default false */ domEvents: false, /** * The value for the touchAction property/fallback. * When set to `compute` it will magically set the correct value based on the added recognizers. * @type {String} * @default compute */ touchAction: TOUCH_ACTION_COMPUTE, /** * @type {Boolean} * @default true */ enable: true, /** * EXPERIMENTAL FEATURE -- can be removed/changed * Change the parent input target element. * If Null, then it is being set the to main element. * @type {Null|EventTarget} * @default null */ inputTarget: null, /** * force an input class * @type {Null|Function} * @default null */ inputClass: null, /** * Default recognizer setup when calling `Hammer()` * When creating a new Manager these will be skipped. * @type {Array} */ preset: [ // RecognizerClass, options, [recognizeWith, ...], [requireFailure, ...] [RotateRecognizer, {enable: false}], [PinchRecognizer, {enable: false}, ['rotate']], [SwipeRecognizer, {direction: DIRECTION_HORIZONTAL}], [PanRecognizer, {direction: DIRECTION_HORIZONTAL}, ['swipe']], [TapRecognizer], [TapRecognizer, {event: 'doubletap', taps: 2}, ['tap']], [PressRecognizer] ], /** * Some CSS properties can be used to improve the working of Hammer. * Add them to this method and they will be set when creating a new Manager. * @namespace */ cssProps: { /** * Disables text selection to improve the dragging gesture. Mainly for desktop browsers. * @type {String} * @default 'none' */ userSelect: 'none', /** * Disable the Windows Phone grippers when pressing an element. * @type {String} * @default 'none' */ touchSelect: 'none', /** * Disables the default callout shown when you touch and hold a touch target. * On iOS, when you touch and hold a touch target such as a link, Safari displays * a callout containing information about the link. This property allows you to disable that callout. * @type {String} * @default 'none' */ touchCallout: 'none', /** * Specifies whether zooming is enabled. Used by IE10> * @type {String} * @default 'none' */ contentZooming: 'none', /** * Specifies that an entire element should be draggable instead of its contents. Mainly for desktop browsers. * @type {String} * @default 'none' */ userDrag: 'none', /** * Overrides the highlight color shown when the user taps a link or a JavaScript * clickable element in iOS. This property obeys the alpha value, if specified. * @type {String} * @default 'rgba(0,0,0,0)' */ tapHighlightColor: 'rgba(0,0,0,0)' } }; var STOP = 1; var FORCED_STOP = 2; /** * Manager * @param {HTMLElement} element * @param {Object} [options] * @constructor */ function Manager(element, options) { this.options = assign({}, Hammer.defaults, options || {}); this.options.inputTarget = this.options.inputTarget || element; this.handlers = {}; this.session = {}; this.recognizers = []; this.oldCssProps = {}; this.element = element; this.input = createInputInstance(this); this.touchAction = new TouchAction(this, this.options.touchAction); toggleCssProps(this, true); each(this.options.recognizers, function(item) { var recognizer = this.add(new (item[0])(item[1])); item[2] && recognizer.recognizeWith(item[2]); item[3] && recognizer.requireFailure(item[3]); }, this); } Manager.prototype = { /** * set options * @param {Object} options * @returns {Manager} */ set: function(options) { assign(this.options, options); // Options that need a little more setup if (options.touchAction) { this.touchAction.update(); } if (options.inputTarget) { // Clean up existing event listeners and reinitialize this.input.destroy(); this.input.target = options.inputTarget; this.input.init(); } return this; }, /** * stop recognizing for this session. * This session will be discarded, when a new [input]start event is fired. * When forced, the recognizer cycle is stopped immediately. * @param {Boolean} [force] */ stop: function(force) { this.session.stopped = force ? FORCED_STOP : STOP; }, /** * run the recognizers! * called by the inputHandler function on every movement of the pointers (touches) * it walks through all the recognizers and tries to detect the gesture that is being made * @param {Object} inputData */ recognize: function(inputData) { var session = this.session; if (session.stopped) { return; } // run the touch-action polyfill this.touchAction.preventDefaults(inputData); var recognizer; var recognizers = this.recognizers; // this holds the recognizer that is being recognized. // so the recognizer's state needs to be BEGAN, CHANGED, ENDED or RECOGNIZED // if no recognizer is detecting a thing, it is set to `null` var curRecognizer = session.curRecognizer; // reset when the last recognizer is recognized // or when we're in a new session if (!curRecognizer || (curRecognizer && curRecognizer.state & STATE_RECOGNIZED)) { curRecognizer = session.curRecognizer = null; } var i = 0; while (i < recognizers.length) { recognizer = recognizers[i]; // find out if we are allowed try to recognize the input for this one. // 1. allow if the session is NOT forced stopped (see the .stop() method) // 2. allow if we still haven't recognized a gesture in this session, or the this recognizer is the one // that is being recognized. // 3. allow if the recognizer is allowed to run simultaneous with the current recognized recognizer. // this can be setup with the `recognizeWith()` method on the recognizer. if (session.stopped !== FORCED_STOP && ( // 1 !curRecognizer || recognizer == curRecognizer || // 2 recognizer.canRecognizeWith(curRecognizer))) { // 3 recognizer.recognize(inputData); } else { recognizer.reset(); } // if the recognizer has been recognizing the input as a valid gesture, we want to store this one as the // current active recognizer. but only if we don't already have an active recognizer if (!curRecognizer && recognizer.state & (STATE_BEGAN | STATE_CHANGED | STATE_ENDED)) { curRecognizer = session.curRecognizer = recognizer; } i++; } }, /** * get a recognizer by its event name. * @param {Recognizer|String} recognizer * @returns {Recognizer|Null} */ get: function(recognizer) { if (recognizer instanceof Recognizer) { return recognizer; } var recognizers = this.recognizers; for (var i = 0; i < recognizers.length; i++) { if (recognizers[i].options.event == recognizer) { return recognizers[i]; } } return null; }, /** * add a recognizer to the manager * existing recognizers with the same event name will be removed * @param {Recognizer} recognizer * @returns {Recognizer|Manager} */ add: function(recognizer) { if (invokeArrayArg(recognizer, 'add', this)) { return this; } // remove existing var existing = this.get(recognizer.options.event); if (existing) { this.remove(existing); } this.recognizers.push(recognizer); recognizer.manager = this; this.touchAction.update(); return recognizer; }, /** * remove a recognizer by name or instance * @param {Recognizer|String} recognizer * @returns {Manager} */ remove: function(recognizer) { if (invokeArrayArg(recognizer, 'remove', this)) { return this; } recognizer = this.get(recognizer); // let's make sure this recognizer exists if (recognizer) { var recognizers = this.recognizers; var index = inArray(recognizers, recognizer); if (index !== -1) { recognizers.splice(index, 1); this.touchAction.update(); } } return this; }, /** * bind event * @param {String} events * @param {Function} handler * @returns {EventEmitter} this */ on: function(events, handler) { if (events === undefined) { return; } if (handler === undefined) { return; } var handlers = this.handlers; each(splitStr(events), function(event) { handlers[event] = handlers[event] || []; handlers[event].push(handler); }); return this; }, /** * unbind event, leave emit blank to remove all handlers * @param {String} events * @param {Function} [handler] * @returns {EventEmitter} this */ off: function(events, handler) { if (events === undefined) { return; } var handlers = this.handlers; each(splitStr(events), function(event) { if (!handler) { delete handlers[event]; } else { handlers[event] && handlers[event].splice(inArray(handlers[event], handler), 1); } }); return this; }, /** * emit event to the listeners * @param {String} event * @param {Object} data */ emit: function(event, data) { // we also want to trigger dom events if (this.options.domEvents) { triggerDomEvent(event, data); } // no handlers, so skip it all var handlers = this.handlers[event] && this.handlers[event].slice(); if (!handlers || !handlers.length) { return; } data.type = event; data.preventDefault = function() { data.srcEvent.preventDefault(); }; var i = 0; while (i < handlers.length) { handlers[i](data); i++; } }, /** * destroy the manager and unbinds all events * it doesn't unbind dom events, that is the user own responsibility */ destroy: function() { this.element && toggleCssProps(this, false); this.handlers = {}; this.session = {}; this.input.destroy(); this.element = null; } }; /** * add/remove the css properties as defined in manager.options.cssProps * @param {Manager} manager * @param {Boolean} add */ function toggleCssProps(manager, add) { var element = manager.element; if (!element.style) { return; } var prop; each(manager.options.cssProps, function(value, name) { prop = prefixed(element.style, name); if (add) { manager.oldCssProps[prop] = element.style[prop]; element.style[prop] = value; } else { element.style[prop] = manager.oldCssProps[prop] || ''; } }); if (!add) { manager.oldCssProps = {}; } } /** * trigger dom event * @param {String} event * @param {Object} data */ function triggerDomEvent(event, data) { var gestureEvent = document.createEvent('Event'); gestureEvent.initEvent(event, true, true); gestureEvent.gesture = data; data.target.dispatchEvent(gestureEvent); } assign(Hammer, { INPUT_START: INPUT_START, INPUT_MOVE: INPUT_MOVE, INPUT_END: INPUT_END, INPUT_CANCEL: INPUT_CANCEL, STATE_POSSIBLE: STATE_POSSIBLE, STATE_BEGAN: STATE_BEGAN, STATE_CHANGED: STATE_CHANGED, STATE_ENDED: STATE_ENDED, STATE_RECOGNIZED: STATE_RECOGNIZED, STATE_CANCELLED: STATE_CANCELLED, STATE_FAILED: STATE_FAILED, DIRECTION_NONE: DIRECTION_NONE, DIRECTION_LEFT: DIRECTION_LEFT, DIRECTION_RIGHT: DIRECTION_RIGHT, DIRECTION_UP: DIRECTION_UP, DIRECTION_DOWN: DIRECTION_DOWN, DIRECTION_HORIZONTAL: DIRECTION_HORIZONTAL, DIRECTION_VERTICAL: DIRECTION_VERTICAL, DIRECTION_ALL: DIRECTION_ALL, Manager: Manager, Input: Input, TouchAction: TouchAction, TouchInput: TouchInput, MouseInput: MouseInput, PointerEventInput: PointerEventInput, TouchMouseInput: TouchMouseInput, SingleTouchInput: SingleTouchInput, Recognizer: Recognizer, AttrRecognizer: AttrRecognizer, Tap: TapRecognizer, Pan: PanRecognizer, Swipe: SwipeRecognizer, Pinch: PinchRecognizer, Rotate: RotateRecognizer, Press: PressRecognizer, on: addEventListeners, off: removeEventListeners, each: each, merge: merge, extend: extend, assign: assign, inherit: inherit, bindFn: bindFn, prefixed: prefixed }); // this prevents errors when Hammer is loaded in the presence of an AMD // style loader but by script tag, not by the loader. var freeGlobal = (typeof window !== 'undefined' ? window : (typeof self !== 'undefined' ? self : {})); // jshint ignore:line freeGlobal.Hammer = Hammer; if (true) { !(__WEBPACK_AMD_DEFINE_RESULT__ = (function() { return Hammer; }).call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else {} })(window, document, 'Hammer'); /***/ }), /* 65 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return _iterableToArray; }); function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } /***/ }), /* 66 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var reactIs = __webpack_require__(23); /** * Copyright 2015, Yahoo! Inc. * Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. */ var REACT_STATICS = { childContextTypes: true, contextType: true, contextTypes: true, defaultProps: true, displayName: true, getDefaultProps: true, getDerivedStateFromError: true, getDerivedStateFromProps: true, mixins: true, propTypes: true, type: true }; var KNOWN_STATICS = { name: true, length: true, prototype: true, caller: true, callee: true, arguments: true, arity: true }; var FORWARD_REF_STATICS = { '$$typeof': true, render: true, defaultProps: true, displayName: true, propTypes: true }; var MEMO_STATICS = { '$$typeof': true, compare: true, defaultProps: true, displayName: true, propTypes: true, type: true }; var TYPE_STATICS = {}; TYPE_STATICS[reactIs.ForwardRef] = FORWARD_REF_STATICS; TYPE_STATICS[reactIs.Memo] = MEMO_STATICS; function getStatics(component) { // React v16.11 and below if (reactIs.isMemo(component)) { return MEMO_STATICS; } // React v16.12 and above return TYPE_STATICS[component['$$typeof']] || REACT_STATICS; } var defineProperty = Object.defineProperty; var getOwnPropertyNames = Object.getOwnPropertyNames; var getOwnPropertySymbols = Object.getOwnPropertySymbols; var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; var getPrototypeOf = Object.getPrototypeOf; var objectPrototype = Object.prototype; function hoistNonReactStatics(targetComponent, sourceComponent, blacklist) { if (typeof sourceComponent !== 'string') { // don't hoist over string (html) components if (objectPrototype) { var inheritedComponent = getPrototypeOf(sourceComponent); if (inheritedComponent && inheritedComponent !== objectPrototype) { hoistNonReactStatics(targetComponent, inheritedComponent, blacklist); } } var keys = getOwnPropertyNames(sourceComponent); if (getOwnPropertySymbols) { keys = keys.concat(getOwnPropertySymbols(sourceComponent)); } var targetStatics = getStatics(targetComponent); var sourceStatics = getStatics(sourceComponent); for (var i = 0; i < keys.length; ++i) { var key = keys[i]; if (!KNOWN_STATICS[key] && !(blacklist && blacklist[key]) && !(sourceStatics && sourceStatics[key]) && !(targetStatics && targetStatics[key])) { var descriptor = getOwnPropertyDescriptor(sourceComponent, key); try { // Avoid failures from read-only properties defineProperty(targetComponent, key, descriptor); } catch (e) {} } } } return targetComponent; } module.exports = hoistNonReactStatics; /***/ }), /* 67 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return _arrayWithHoles; }); function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } /***/ }), /* 68 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return _nonIterableRest; }); function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } /***/ }), /* 69 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return _typeof; }); function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } /***/ }), /* 70 */ /***/ (function(module, exports) { function _extends() { module.exports = _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } module.exports = _extends; /***/ }), /* 71 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* WEBPACK VAR INJECTION */(function(global) {/**! * @fileOverview Kickass library to create and place poppers near their reference elements. * @version 1.16.1 * @license * Copyright (c) 2016 Federico Zivolo and contributors * * 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. */ var isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined' && typeof navigator !== 'undefined'; var timeoutDuration = function () { var longerTimeoutBrowsers = ['Edge', 'Trident', 'Firefox']; for (var i = 0; i < longerTimeoutBrowsers.length; i += 1) { if (isBrowser && navigator.userAgent.indexOf(longerTimeoutBrowsers[i]) >= 0) { return 1; } } return 0; }(); function microtaskDebounce(fn) { var called = false; return function () { if (called) { return; } called = true; window.Promise.resolve().then(function () { called = false; fn(); }); }; } function taskDebounce(fn) { var scheduled = false; return function () { if (!scheduled) { scheduled = true; setTimeout(function () { scheduled = false; fn(); }, timeoutDuration); } }; } var supportsMicroTasks = isBrowser && window.Promise; /** * Create a debounced version of a method, that's asynchronously deferred * but called in the minimum time possible. * * @method * @memberof Popper.Utils * @argument {Function} fn * @returns {Function} */ var debounce = supportsMicroTasks ? microtaskDebounce : taskDebounce; /** * Check if the given variable is a function * @method * @memberof Popper.Utils * @argument {Any} functionToCheck - variable to check * @returns {Boolean} answer to: is a function? */ function isFunction(functionToCheck) { var getType = {}; return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]'; } /** * Get CSS computed property of the given element * @method * @memberof Popper.Utils * @argument {Eement} element * @argument {String} property */ function getStyleComputedProperty(element, property) { if (element.nodeType !== 1) { return []; } // NOTE: 1 DOM access here var window = element.ownerDocument.defaultView; var css = window.getComputedStyle(element, null); return property ? css[property] : css; } /** * Returns the parentNode or the host of the element * @method * @memberof Popper.Utils * @argument {Element} element * @returns {Element} parent */ function getParentNode(element) { if (element.nodeName === 'HTML') { return element; } return element.parentNode || element.host; } /** * Returns the scrolling parent of the given element * @method * @memberof Popper.Utils * @argument {Element} element * @returns {Element} scroll parent */ function getScrollParent(element) { // Return body, `getScroll` will take care to get the correct `scrollTop` from it if (!element) { return document.body; } switch (element.nodeName) { case 'HTML': case 'BODY': return element.ownerDocument.body; case '#document': return element.body; } // Firefox want us to check `-x` and `-y` variations as well var _getStyleComputedProp = getStyleComputedProperty(element), overflow = _getStyleComputedProp.overflow, overflowX = _getStyleComputedProp.overflowX, overflowY = _getStyleComputedProp.overflowY; if (/(auto|scroll|overlay)/.test(overflow + overflowY + overflowX)) { return element; } return getScrollParent(getParentNode(element)); } /** * Returns the reference node of the reference object, or the reference object itself. * @method * @memberof Popper.Utils * @param {Element|Object} reference - the reference element (the popper will be relative to this) * @returns {Element} parent */ function getReferenceNode(reference) { return reference && reference.referenceNode ? reference.referenceNode : reference; } var isIE11 = isBrowser && !!(window.MSInputMethodContext && document.documentMode); var isIE10 = isBrowser && /MSIE 10/.test(navigator.userAgent); /** * Determines if the browser is Internet Explorer * @method * @memberof Popper.Utils * @param {Number} version to check * @returns {Boolean} isIE */ function isIE(version) { if (version === 11) { return isIE11; } if (version === 10) { return isIE10; } return isIE11 || isIE10; } /** * Returns the offset parent of the given element * @method * @memberof Popper.Utils * @argument {Element} element * @returns {Element} offset parent */ function getOffsetParent(element) { if (!element) { return document.documentElement; } var noOffsetParent = isIE(10) ? document.body : null; // NOTE: 1 DOM access here var offsetParent = element.offsetParent || null; // Skip hidden elements which don't have an offsetParent while (offsetParent === noOffsetParent && element.nextElementSibling) { offsetParent = (element = element.nextElementSibling).offsetParent; } var nodeName = offsetParent && offsetParent.nodeName; if (!nodeName || nodeName === 'BODY' || nodeName === 'HTML') { return element ? element.ownerDocument.documentElement : document.documentElement; } // .offsetParent will return the closest TH, TD or TABLE in case // no offsetParent is present, I hate this job... if (['TH', 'TD', 'TABLE'].indexOf(offsetParent.nodeName) !== -1 && getStyleComputedProperty(offsetParent, 'position') === 'static') { return getOffsetParent(offsetParent); } return offsetParent; } function isOffsetContainer(element) { var nodeName = element.nodeName; if (nodeName === 'BODY') { return false; } return nodeName === 'HTML' || getOffsetParent(element.firstElementChild) === element; } /** * Finds the root node (document, shadowDOM root) of the given element * @method * @memberof Popper.Utils * @argument {Element} node * @returns {Element} root node */ function getRoot(node) { if (node.parentNode !== null) { return getRoot(node.parentNode); } return node; } /** * Finds the offset parent common to the two provided nodes * @method * @memberof Popper.Utils * @argument {Element} element1 * @argument {Element} element2 * @returns {Element} common offset parent */ function findCommonOffsetParent(element1, element2) { // This check is needed to avoid errors in case one of the elements isn't defined for any reason if (!element1 || !element1.nodeType || !element2 || !element2.nodeType) { return document.documentElement; } // Here we make sure to give as "start" the element that comes first in the DOM var order = element1.compareDocumentPosition(element2) & Node.DOCUMENT_POSITION_FOLLOWING; var start = order ? element1 : element2; var end = order ? element2 : element1; // Get common ancestor container var range = document.createRange(); range.setStart(start, 0); range.setEnd(end, 0); var commonAncestorContainer = range.commonAncestorContainer; // Both nodes are inside #document if (element1 !== commonAncestorContainer && element2 !== commonAncestorContainer || start.contains(end)) { if (isOffsetContainer(commonAncestorContainer)) { return commonAncestorContainer; } return getOffsetParent(commonAncestorContainer); } // one of the nodes is inside shadowDOM, find which one var element1root = getRoot(element1); if (element1root.host) { return findCommonOffsetParent(element1root.host, element2); } else { return findCommonOffsetParent(element1, getRoot(element2).host); } } /** * Gets the scroll value of the given element in the given side (top and left) * @method * @memberof Popper.Utils * @argument {Element} element * @argument {String} side `top` or `left` * @returns {number} amount of scrolled pixels */ function getScroll(element) { var side = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'top'; var upperSide = side === 'top' ? 'scrollTop' : 'scrollLeft'; var nodeName = element.nodeName; if (nodeName === 'BODY' || nodeName === 'HTML') { var html = element.ownerDocument.documentElement; var scrollingElement = element.ownerDocument.scrollingElement || html; return scrollingElement[upperSide]; } return element[upperSide]; } /* * Sum or subtract the element scroll values (left and top) from a given rect object * @method * @memberof Popper.Utils * @param {Object} rect - Rect object you want to change * @param {HTMLElement} element - The element from the function reads the scroll values * @param {Boolean} subtract - set to true if you want to subtract the scroll values * @return {Object} rect - The modifier rect object */ function includeScroll(rect, element) { var subtract = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; var scrollTop = getScroll(element, 'top'); var scrollLeft = getScroll(element, 'left'); var modifier = subtract ? -1 : 1; rect.top += scrollTop * modifier; rect.bottom += scrollTop * modifier; rect.left += scrollLeft * modifier; rect.right += scrollLeft * modifier; return rect; } /* * Helper to detect borders of a given element * @method * @memberof Popper.Utils * @param {CSSStyleDeclaration} styles * Result of `getStyleComputedProperty` on the given element * @param {String} axis - `x` or `y` * @return {number} borders - The borders size of the given axis */ function getBordersSize(styles, axis) { var sideA = axis === 'x' ? 'Left' : 'Top'; var sideB = sideA === 'Left' ? 'Right' : 'Bottom'; return parseFloat(styles['border' + sideA + 'Width']) + parseFloat(styles['border' + sideB + 'Width']); } function getSize(axis, body, html, computedStyle) { return Math.max(body['offset' + axis], body['scroll' + axis], html['client' + axis], html['offset' + axis], html['scroll' + axis], isIE(10) ? parseInt(html['offset' + axis]) + parseInt(computedStyle['margin' + (axis === 'Height' ? 'Top' : 'Left')]) + parseInt(computedStyle['margin' + (axis === 'Height' ? 'Bottom' : 'Right')]) : 0); } function getWindowSizes(document) { var body = document.body; var html = document.documentElement; var computedStyle = isIE(10) && getComputedStyle(html); return { height: getSize('Height', body, html, computedStyle), width: getSize('Width', body, html, computedStyle) }; } var classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; var createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var defineProperty = function (obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; /** * Given element offsets, generate an output similar to getBoundingClientRect * @method * @memberof Popper.Utils * @argument {Object} offsets * @returns {Object} ClientRect like output */ function getClientRect(offsets) { return _extends({}, offsets, { right: offsets.left + offsets.width, bottom: offsets.top + offsets.height }); } /** * Get bounding client rect of given element * @method * @memberof Popper.Utils * @param {HTMLElement} element * @return {Object} client rect */ function getBoundingClientRect(element) { var rect = {}; // IE10 10 FIX: Please, don't ask, the element isn't // considered in DOM in some circumstances... // This isn't reproducible in IE10 compatibility mode of IE11 try { if (isIE(10)) { rect = element.getBoundingClientRect(); var scrollTop = getScroll(element, 'top'); var scrollLeft = getScroll(element, 'left'); rect.top += scrollTop; rect.left += scrollLeft; rect.bottom += scrollTop; rect.right += scrollLeft; } else { rect = element.getBoundingClientRect(); } } catch (e) {} var result = { left: rect.left, top: rect.top, width: rect.right - rect.left, height: rect.bottom - rect.top }; // subtract scrollbar size from sizes var sizes = element.nodeName === 'HTML' ? getWindowSizes(element.ownerDocument) : {}; var width = sizes.width || element.clientWidth || result.width; var height = sizes.height || element.clientHeight || result.height; var horizScrollbar = element.offsetWidth - width; var vertScrollbar = element.offsetHeight - height; // if an hypothetical scrollbar is detected, we must be sure it's not a `border` // we make this check conditional for performance reasons if (horizScrollbar || vertScrollbar) { var styles = getStyleComputedProperty(element); horizScrollbar -= getBordersSize(styles, 'x'); vertScrollbar -= getBordersSize(styles, 'y'); result.width -= horizScrollbar; result.height -= vertScrollbar; } return getClientRect(result); } function getOffsetRectRelativeToArbitraryNode(children, parent) { var fixedPosition = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; var isIE10 = isIE(10); var isHTML = parent.nodeName === 'HTML'; var childrenRect = getBoundingClientRect(children); var parentRect = getBoundingClientRect(parent); var scrollParent = getScrollParent(children); var styles = getStyleComputedProperty(parent); var borderTopWidth = parseFloat(styles.borderTopWidth); var borderLeftWidth = parseFloat(styles.borderLeftWidth); // In cases where the parent is fixed, we must ignore negative scroll in offset calc if (fixedPosition && isHTML) { parentRect.top = Math.max(parentRect.top, 0); parentRect.left = Math.max(parentRect.left, 0); } var offsets = getClientRect({ top: childrenRect.top - parentRect.top - borderTopWidth, left: childrenRect.left - parentRect.left - borderLeftWidth, width: childrenRect.width, height: childrenRect.height }); offsets.marginTop = 0; offsets.marginLeft = 0; // Subtract margins of documentElement in case it's being used as parent // we do this only on HTML because it's the only element that behaves // differently when margins are applied to it. The margins are included in // the box of the documentElement, in the other cases not. if (!isIE10 && isHTML) { var marginTop = parseFloat(styles.marginTop); var marginLeft = parseFloat(styles.marginLeft); offsets.top -= borderTopWidth - marginTop; offsets.bottom -= borderTopWidth - marginTop; offsets.left -= borderLeftWidth - marginLeft; offsets.right -= borderLeftWidth - marginLeft; // Attach marginTop and marginLeft because in some circumstances we may need them offsets.marginTop = marginTop; offsets.marginLeft = marginLeft; } if (isIE10 && !fixedPosition ? parent.contains(scrollParent) : parent === scrollParent && scrollParent.nodeName !== 'BODY') { offsets = includeScroll(offsets, parent); } return offsets; } function getViewportOffsetRectRelativeToArtbitraryNode(element) { var excludeScroll = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; var html = element.ownerDocument.documentElement; var relativeOffset = getOffsetRectRelativeToArbitraryNode(element, html); var width = Math.max(html.clientWidth, window.innerWidth || 0); var height = Math.max(html.clientHeight, window.innerHeight || 0); var scrollTop = !excludeScroll ? getScroll(html) : 0; var scrollLeft = !excludeScroll ? getScroll(html, 'left') : 0; var offset = { top: scrollTop - relativeOffset.top + relativeOffset.marginTop, left: scrollLeft - relativeOffset.left + relativeOffset.marginLeft, width: width, height: height }; return getClientRect(offset); } /** * Check if the given element is fixed or is inside a fixed parent * @method * @memberof Popper.Utils * @argument {Element} element * @argument {Element} customContainer * @returns {Boolean} answer to "isFixed?" */ function isFixed(element) { var nodeName = element.nodeName; if (nodeName === 'BODY' || nodeName === 'HTML') { return false; } if (getStyleComputedProperty(element, 'position') === 'fixed') { return true; } var parentNode = getParentNode(element); if (!parentNode) { return false; } return isFixed(parentNode); } /** * Finds the first parent of an element that has a transformed property defined * @method * @memberof Popper.Utils * @argument {Element} element * @returns {Element} first transformed parent or documentElement */ function getFixedPositionOffsetParent(element) { // This check is needed to avoid errors in case one of the elements isn't defined for any reason if (!element || !element.parentElement || isIE()) { return document.documentElement; } var el = element.parentElement; while (el && getStyleComputedProperty(el, 'transform') === 'none') { el = el.parentElement; } return el || document.documentElement; } /** * Computed the boundaries limits and return them * @method * @memberof Popper.Utils * @param {HTMLElement} popper * @param {HTMLElement} reference * @param {number} padding * @param {HTMLElement} boundariesElement - Element used to define the boundaries * @param {Boolean} fixedPosition - Is in fixed position mode * @returns {Object} Coordinates of the boundaries */ function getBoundaries(popper, reference, padding, boundariesElement) { var fixedPosition = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false; // NOTE: 1 DOM access here var boundaries = { top: 0, left: 0 }; var offsetParent = fixedPosition ? getFixedPositionOffsetParent(popper) : findCommonOffsetParent(popper, getReferenceNode(reference)); // Handle viewport case if (boundariesElement === 'viewport') { boundaries = getViewportOffsetRectRelativeToArtbitraryNode(offsetParent, fixedPosition); } else { // Handle other cases based on DOM element used as boundaries var boundariesNode = void 0; if (boundariesElement === 'scrollParent') { boundariesNode = getScrollParent(getParentNode(reference)); if (boundariesNode.nodeName === 'BODY') { boundariesNode = popper.ownerDocument.documentElement; } } else if (boundariesElement === 'window') { boundariesNode = popper.ownerDocument.documentElement; } else { boundariesNode = boundariesElement; } var offsets = getOffsetRectRelativeToArbitraryNode(boundariesNode, offsetParent, fixedPosition); // In case of HTML, we need a different computation if (boundariesNode.nodeName === 'HTML' && !isFixed(offsetParent)) { var _getWindowSizes = getWindowSizes(popper.ownerDocument), height = _getWindowSizes.height, width = _getWindowSizes.width; boundaries.top += offsets.top - offsets.marginTop; boundaries.bottom = height + offsets.top; boundaries.left += offsets.left - offsets.marginLeft; boundaries.right = width + offsets.left; } else { // for all the other DOM elements, this one is good boundaries = offsets; } } // Add paddings padding = padding || 0; var isPaddingNumber = typeof padding === 'number'; boundaries.left += isPaddingNumber ? padding : padding.left || 0; boundaries.top += isPaddingNumber ? padding : padding.top || 0; boundaries.right -= isPaddingNumber ? padding : padding.right || 0; boundaries.bottom -= isPaddingNumber ? padding : padding.bottom || 0; return boundaries; } function getArea(_ref) { var width = _ref.width, height = _ref.height; return width * height; } /** * Utility used to transform the `auto` placement to the placement with more * available space. * @method * @memberof Popper.Utils * @argument {Object} data - The data object generated by update method * @argument {Object} options - Modifiers configuration and options * @returns {Object} The data object, properly modified */ function computeAutoPlacement(placement, refRect, popper, reference, boundariesElement) { var padding = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 0; if (placement.indexOf('auto') === -1) { return placement; } var boundaries = getBoundaries(popper, reference, padding, boundariesElement); var rects = { top: { width: boundaries.width, height: refRect.top - boundaries.top }, right: { width: boundaries.right - refRect.right, height: boundaries.height }, bottom: { width: boundaries.width, height: boundaries.bottom - refRect.bottom }, left: { width: refRect.left - boundaries.left, height: boundaries.height } }; var sortedAreas = Object.keys(rects).map(function (key) { return _extends({ key: key }, rects[key], { area: getArea(rects[key]) }); }).sort(function (a, b) { return b.area - a.area; }); var filteredAreas = sortedAreas.filter(function (_ref2) { var width = _ref2.width, height = _ref2.height; return width >= popper.clientWidth && height >= popper.clientHeight; }); var computedPlacement = filteredAreas.length > 0 ? filteredAreas[0].key : sortedAreas[0].key; var variation = placement.split('-')[1]; return computedPlacement + (variation ? '-' + variation : ''); } /** * Get offsets to the reference element * @method * @memberof Popper.Utils * @param {Object} state * @param {Element} popper - the popper element * @param {Element} reference - the reference element (the popper will be relative to this) * @param {Element} fixedPosition - is in fixed position mode * @returns {Object} An object containing the offsets which will be applied to the popper */ function getReferenceOffsets(state, popper, reference) { var fixedPosition = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; var commonOffsetParent = fixedPosition ? getFixedPositionOffsetParent(popper) : findCommonOffsetParent(popper, getReferenceNode(reference)); return getOffsetRectRelativeToArbitraryNode(reference, commonOffsetParent, fixedPosition); } /** * Get the outer sizes of the given element (offset size + margins) * @method * @memberof Popper.Utils * @argument {Element} element * @returns {Object} object containing width and height properties */ function getOuterSizes(element) { var window = element.ownerDocument.defaultView; var styles = window.getComputedStyle(element); var x = parseFloat(styles.marginTop || 0) + parseFloat(styles.marginBottom || 0); var y = parseFloat(styles.marginLeft || 0) + parseFloat(styles.marginRight || 0); var result = { width: element.offsetWidth + y, height: element.offsetHeight + x }; return result; } /** * Get the opposite placement of the given one * @method * @memberof Popper.Utils * @argument {String} placement * @returns {String} flipped placement */ function getOppositePlacement(placement) { var hash = { left: 'right', right: 'left', bottom: 'top', top: 'bottom' }; return placement.replace(/left|right|bottom|top/g, function (matched) { return hash[matched]; }); } /** * Get offsets to the popper * @method * @memberof Popper.Utils * @param {Object} position - CSS position the Popper will get applied * @param {HTMLElement} popper - the popper element * @param {Object} referenceOffsets - the reference offsets (the popper will be relative to this) * @param {String} placement - one of the valid placement options * @returns {Object} popperOffsets - An object containing the offsets which will be applied to the popper */ function getPopperOffsets(popper, referenceOffsets, placement) { placement = placement.split('-')[0]; // Get popper node sizes var popperRect = getOuterSizes(popper); // Add position, width and height to our offsets object var popperOffsets = { width: popperRect.width, height: popperRect.height }; // depending by the popper placement we have to compute its offsets slightly differently var isHoriz = ['right', 'left'].indexOf(placement) !== -1; var mainSide = isHoriz ? 'top' : 'left'; var secondarySide = isHoriz ? 'left' : 'top'; var measurement = isHoriz ? 'height' : 'width'; var secondaryMeasurement = !isHoriz ? 'height' : 'width'; popperOffsets[mainSide] = referenceOffsets[mainSide] + referenceOffsets[measurement] / 2 - popperRect[measurement] / 2; if (placement === secondarySide) { popperOffsets[secondarySide] = referenceOffsets[secondarySide] - popperRect[secondaryMeasurement]; } else { popperOffsets[secondarySide] = referenceOffsets[getOppositePlacement(secondarySide)]; } return popperOffsets; } /** * Mimics the `find` method of Array * @method * @memberof Popper.Utils * @argument {Array} arr * @argument prop * @argument value * @returns index or -1 */ function find(arr, check) { // use native find if supported if (Array.prototype.find) { return arr.find(check); } // use `filter` to obtain the same behavior of `find` return arr.filter(check)[0]; } /** * Return the index of the matching object * @method * @memberof Popper.Utils * @argument {Array} arr * @argument prop * @argument value * @returns index or -1 */ function findIndex(arr, prop, value) { // use native findIndex if supported if (Array.prototype.findIndex) { return arr.findIndex(function (cur) { return cur[prop] === value; }); } // use `find` + `indexOf` if `findIndex` isn't supported var match = find(arr, function (obj) { return obj[prop] === value; }); return arr.indexOf(match); } /** * Loop trough the list of modifiers and run them in order, * each of them will then edit the data object. * @method * @memberof Popper.Utils * @param {dataObject} data * @param {Array} modifiers * @param {String} ends - Optional modifier name used as stopper * @returns {dataObject} */ function runModifiers(modifiers, data, ends) { var modifiersToRun = ends === undefined ? modifiers : modifiers.slice(0, findIndex(modifiers, 'name', ends)); modifiersToRun.forEach(function (modifier) { if (modifier['function']) { // eslint-disable-line dot-notation console.warn('`modifier.function` is deprecated, use `modifier.fn`!'); } var fn = modifier['function'] || modifier.fn; // eslint-disable-line dot-notation if (modifier.enabled && isFunction(fn)) { // Add properties to offsets to make them a complete clientRect object // we do this before each modifier to make sure the previous one doesn't // mess with these values data.offsets.popper = getClientRect(data.offsets.popper); data.offsets.reference = getClientRect(data.offsets.reference); data = fn(data, modifier); } }); return data; } /** * Updates the position of the popper, computing the new offsets and applying * the new style.
* Prefer `scheduleUpdate` over `update` because of performance reasons. * @method * @memberof Popper */ function update() { // if popper is destroyed, don't perform any further update if (this.state.isDestroyed) { return; } var data = { instance: this, styles: {}, arrowStyles: {}, attributes: {}, flipped: false, offsets: {} }; // compute reference element offsets data.offsets.reference = getReferenceOffsets(this.state, this.popper, this.reference, this.options.positionFixed); // compute auto placement, store placement inside the data object, // modifiers will be able to edit `placement` if needed // and refer to originalPlacement to know the original value data.placement = computeAutoPlacement(this.options.placement, data.offsets.reference, this.popper, this.reference, this.options.modifiers.flip.boundariesElement, this.options.modifiers.flip.padding); // store the computed placement inside `originalPlacement` data.originalPlacement = data.placement; data.positionFixed = this.options.positionFixed; // compute the popper offsets data.offsets.popper = getPopperOffsets(this.popper, data.offsets.reference, data.placement); data.offsets.popper.position = this.options.positionFixed ? 'fixed' : 'absolute'; // run the modifiers data = runModifiers(this.modifiers, data); // the first `update` will call `onCreate` callback // the other ones will call `onUpdate` callback if (!this.state.isCreated) { this.state.isCreated = true; this.options.onCreate(data); } else { this.options.onUpdate(data); } } /** * Helper used to know if the given modifier is enabled. * @method * @memberof Popper.Utils * @returns {Boolean} */ function isModifierEnabled(modifiers, modifierName) { return modifiers.some(function (_ref) { var name = _ref.name, enabled = _ref.enabled; return enabled && name === modifierName; }); } /** * Get the prefixed supported property name * @method * @memberof Popper.Utils * @argument {String} property (camelCase) * @returns {String} prefixed property (camelCase or PascalCase, depending on the vendor prefix) */ function getSupportedPropertyName(property) { var prefixes = [false, 'ms', 'Webkit', 'Moz', 'O']; var upperProp = property.charAt(0).toUpperCase() + property.slice(1); for (var i = 0; i < prefixes.length; i++) { var prefix = prefixes[i]; var toCheck = prefix ? '' + prefix + upperProp : property; if (typeof document.body.style[toCheck] !== 'undefined') { return toCheck; } } return null; } /** * Destroys the popper. * @method * @memberof Popper */ function destroy() { this.state.isDestroyed = true; // touch DOM only if `applyStyle` modifier is enabled if (isModifierEnabled(this.modifiers, 'applyStyle')) { this.popper.removeAttribute('x-placement'); this.popper.style.position = ''; this.popper.style.top = ''; this.popper.style.left = ''; this.popper.style.right = ''; this.popper.style.bottom = ''; this.popper.style.willChange = ''; this.popper.style[getSupportedPropertyName('transform')] = ''; } this.disableEventListeners(); // remove the popper if user explicitly asked for the deletion on destroy // do not use `remove` because IE11 doesn't support it if (this.options.removeOnDestroy) { this.popper.parentNode.removeChild(this.popper); } return this; } /** * Get the window associated with the element * @argument {Element} element * @returns {Window} */ function getWindow(element) { var ownerDocument = element.ownerDocument; return ownerDocument ? ownerDocument.defaultView : window; } function attachToScrollParents(scrollParent, event, callback, scrollParents) { var isBody = scrollParent.nodeName === 'BODY'; var target = isBody ? scrollParent.ownerDocument.defaultView : scrollParent; target.addEventListener(event, callback, { passive: true }); if (!isBody) { attachToScrollParents(getScrollParent(target.parentNode), event, callback, scrollParents); } scrollParents.push(target); } /** * Setup needed event listeners used to update the popper position * @method * @memberof Popper.Utils * @private */ function setupEventListeners(reference, options, state, updateBound) { // Resize event listener on window state.updateBound = updateBound; getWindow(reference).addEventListener('resize', state.updateBound, { passive: true }); // Scroll event listener on scroll parents var scrollElement = getScrollParent(reference); attachToScrollParents(scrollElement, 'scroll', state.updateBound, state.scrollParents); state.scrollElement = scrollElement; state.eventsEnabled = true; return state; } /** * It will add resize/scroll events and start recalculating * position of the popper element when they are triggered. * @method * @memberof Popper */ function enableEventListeners() { if (!this.state.eventsEnabled) { this.state = setupEventListeners(this.reference, this.options, this.state, this.scheduleUpdate); } } /** * Remove event listeners used to update the popper position * @method * @memberof Popper.Utils * @private */ function removeEventListeners(reference, state) { // Remove resize event listener on window getWindow(reference).removeEventListener('resize', state.updateBound); // Remove scroll event listener on scroll parents state.scrollParents.forEach(function (target) { target.removeEventListener('scroll', state.updateBound); }); // Reset state state.updateBound = null; state.scrollParents = []; state.scrollElement = null; state.eventsEnabled = false; return state; } /** * It will remove resize/scroll events and won't recalculate popper position * when they are triggered. It also won't trigger `onUpdate` callback anymore, * unless you call `update` method manually. * @method * @memberof Popper */ function disableEventListeners() { if (this.state.eventsEnabled) { cancelAnimationFrame(this.scheduleUpdate); this.state = removeEventListeners(this.reference, this.state); } } /** * Tells if a given input is a number * @method * @memberof Popper.Utils * @param {*} input to check * @return {Boolean} */ function isNumeric(n) { return n !== '' && !isNaN(parseFloat(n)) && isFinite(n); } /** * Set the style to the given popper * @method * @memberof Popper.Utils * @argument {Element} element - Element to apply the style to * @argument {Object} styles * Object with a list of properties and values which will be applied to the element */ function setStyles(element, styles) { Object.keys(styles).forEach(function (prop) { var unit = ''; // add unit if the value is numeric and is one of the following if (['width', 'height', 'top', 'right', 'bottom', 'left'].indexOf(prop) !== -1 && isNumeric(styles[prop])) { unit = 'px'; } element.style[prop] = styles[prop] + unit; }); } /** * Set the attributes to the given popper * @method * @memberof Popper.Utils * @argument {Element} element - Element to apply the attributes to * @argument {Object} styles * Object with a list of properties and values which will be applied to the element */ function setAttributes(element, attributes) { Object.keys(attributes).forEach(function (prop) { var value = attributes[prop]; if (value !== false) { element.setAttribute(prop, attributes[prop]); } else { element.removeAttribute(prop); } }); } /** * @function * @memberof Modifiers * @argument {Object} data - The data object generated by `update` method * @argument {Object} data.styles - List of style properties - values to apply to popper element * @argument {Object} data.attributes - List of attribute properties - values to apply to popper element * @argument {Object} options - Modifiers configuration and options * @returns {Object} The same data object */ function applyStyle(data) { // any property present in `data.styles` will be applied to the popper, // in this way we can make the 3rd party modifiers add custom styles to it // Be aware, modifiers could override the properties defined in the previous // lines of this modifier! setStyles(data.instance.popper, data.styles); // any property present in `data.attributes` will be applied to the popper, // they will be set as HTML attributes of the element setAttributes(data.instance.popper, data.attributes); // if arrowElement is defined and arrowStyles has some properties if (data.arrowElement && Object.keys(data.arrowStyles).length) { setStyles(data.arrowElement, data.arrowStyles); } return data; } /** * Set the x-placement attribute before everything else because it could be used * to add margins to the popper margins needs to be calculated to get the * correct popper offsets. * @method * @memberof Popper.modifiers * @param {HTMLElement} reference - The reference element used to position the popper * @param {HTMLElement} popper - The HTML element used as popper * @param {Object} options - Popper.js options */ function applyStyleOnLoad(reference, popper, options, modifierOptions, state) { // compute reference element offsets var referenceOffsets = getReferenceOffsets(state, popper, reference, options.positionFixed); // compute auto placement, store placement inside the data object, // modifiers will be able to edit `placement` if needed // and refer to originalPlacement to know the original value var placement = computeAutoPlacement(options.placement, referenceOffsets, popper, reference, options.modifiers.flip.boundariesElement, options.modifiers.flip.padding); popper.setAttribute('x-placement', placement); // Apply `position` to popper before anything else because // without the position applied we can't guarantee correct computations setStyles(popper, { position: options.positionFixed ? 'fixed' : 'absolute' }); return options; } /** * @function * @memberof Popper.Utils * @argument {Object} data - The data object generated by `update` method * @argument {Boolean} shouldRound - If the offsets should be rounded at all * @returns {Object} The popper's position offsets rounded * * The tale of pixel-perfect positioning. It's still not 100% perfect, but as * good as it can be within reason. * Discussion here: https://github.com/FezVrasta/popper.js/pull/715 * * Low DPI screens cause a popper to be blurry if not using full pixels (Safari * as well on High DPI screens). * * Firefox prefers no rounding for positioning and does not have blurriness on * high DPI screens. * * Only horizontal placement and left/right values need to be considered. */ function getRoundedOffsets(data, shouldRound) { var _data$offsets = data.offsets, popper = _data$offsets.popper, reference = _data$offsets.reference; var round = Math.round, floor = Math.floor; var noRound = function noRound(v) { return v; }; var referenceWidth = round(reference.width); var popperWidth = round(popper.width); var isVertical = ['left', 'right'].indexOf(data.placement) !== -1; var isVariation = data.placement.indexOf('-') !== -1; var sameWidthParity = referenceWidth % 2 === popperWidth % 2; var bothOddWidth = referenceWidth % 2 === 1 && popperWidth % 2 === 1; var horizontalToInteger = !shouldRound ? noRound : isVertical || isVariation || sameWidthParity ? round : floor; var verticalToInteger = !shouldRound ? noRound : round; return { left: horizontalToInteger(bothOddWidth && !isVariation && shouldRound ? popper.left - 1 : popper.left), top: verticalToInteger(popper.top), bottom: verticalToInteger(popper.bottom), right: horizontalToInteger(popper.right) }; } var isFirefox = isBrowser && /Firefox/i.test(navigator.userAgent); /** * @function * @memberof Modifiers * @argument {Object} data - The data object generated by `update` method * @argument {Object} options - Modifiers configuration and options * @returns {Object} The data object, properly modified */ function computeStyle(data, options) { var x = options.x, y = options.y; var popper = data.offsets.popper; // Remove this legacy support in Popper.js v2 var legacyGpuAccelerationOption = find(data.instance.modifiers, function (modifier) { return modifier.name === 'applyStyle'; }).gpuAcceleration; if (legacyGpuAccelerationOption !== undefined) { console.warn('WARNING: `gpuAcceleration` option moved to `computeStyle` modifier and will not be supported in future versions of Popper.js!'); } var gpuAcceleration = legacyGpuAccelerationOption !== undefined ? legacyGpuAccelerationOption : options.gpuAcceleration; var offsetParent = getOffsetParent(data.instance.popper); var offsetParentRect = getBoundingClientRect(offsetParent); // Styles var styles = { position: popper.position }; var offsets = getRoundedOffsets(data, window.devicePixelRatio < 2 || !isFirefox); var sideA = x === 'bottom' ? 'top' : 'bottom'; var sideB = y === 'right' ? 'left' : 'right'; // if gpuAcceleration is set to `true` and transform is supported, // we use `translate3d` to apply the position to the popper we // automatically use the supported prefixed version if needed var prefixedProperty = getSupportedPropertyName('transform'); // now, let's make a step back and look at this code closely (wtf?) // If the content of the popper grows once it's been positioned, it // may happen that the popper gets misplaced because of the new content // overflowing its reference element // To avoid this problem, we provide two options (x and y), which allow // the consumer to define the offset origin. // If we position a popper on top of a reference element, we can set // `x` to `top` to make the popper grow towards its top instead of // its bottom. var left = void 0, top = void 0; if (sideA === 'bottom') { // when offsetParent is the positioning is relative to the bottom of the screen (excluding the scrollbar) // and not the bottom of the html element if (offsetParent.nodeName === 'HTML') { top = -offsetParent.clientHeight + offsets.bottom; } else { top = -offsetParentRect.height + offsets.bottom; } } else { top = offsets.top; } if (sideB === 'right') { if (offsetParent.nodeName === 'HTML') { left = -offsetParent.clientWidth + offsets.right; } else { left = -offsetParentRect.width + offsets.right; } } else { left = offsets.left; } if (gpuAcceleration && prefixedProperty) { styles[prefixedProperty] = 'translate3d(' + left + 'px, ' + top + 'px, 0)'; styles[sideA] = 0; styles[sideB] = 0; styles.willChange = 'transform'; } else { // othwerise, we use the standard `top`, `left`, `bottom` and `right` properties var invertTop = sideA === 'bottom' ? -1 : 1; var invertLeft = sideB === 'right' ? -1 : 1; styles[sideA] = top * invertTop; styles[sideB] = left * invertLeft; styles.willChange = sideA + ', ' + sideB; } // Attributes var attributes = { 'x-placement': data.placement }; // Update `data` attributes, styles and arrowStyles data.attributes = _extends({}, attributes, data.attributes); data.styles = _extends({}, styles, data.styles); data.arrowStyles = _extends({}, data.offsets.arrow, data.arrowStyles); return data; } /** * Helper used to know if the given modifier depends from another one.
* It checks if the needed modifier is listed and enabled. * @method * @memberof Popper.Utils * @param {Array} modifiers - list of modifiers * @param {String} requestingName - name of requesting modifier * @param {String} requestedName - name of requested modifier * @returns {Boolean} */ function isModifierRequired(modifiers, requestingName, requestedName) { var requesting = find(modifiers, function (_ref) { var name = _ref.name; return name === requestingName; }); var isRequired = !!requesting && modifiers.some(function (modifier) { return modifier.name === requestedName && modifier.enabled && modifier.order < requesting.order; }); if (!isRequired) { var _requesting = '`' + requestingName + '`'; var requested = '`' + requestedName + '`'; console.warn(requested + ' modifier is required by ' + _requesting + ' modifier in order to work, be sure to include it before ' + _requesting + '!'); } return isRequired; } /** * @function * @memberof Modifiers * @argument {Object} data - The data object generated by update method * @argument {Object} options - Modifiers configuration and options * @returns {Object} The data object, properly modified */ function arrow(data, options) { var _data$offsets$arrow; // arrow depends on keepTogether in order to work if (!isModifierRequired(data.instance.modifiers, 'arrow', 'keepTogether')) { return data; } var arrowElement = options.element; // if arrowElement is a string, suppose it's a CSS selector if (typeof arrowElement === 'string') { arrowElement = data.instance.popper.querySelector(arrowElement); // if arrowElement is not found, don't run the modifier if (!arrowElement) { return data; } } else { // if the arrowElement isn't a query selector we must check that the // provided DOM node is child of its popper node if (!data.instance.popper.contains(arrowElement)) { console.warn('WARNING: `arrow.element` must be child of its popper element!'); return data; } } var placement = data.placement.split('-')[0]; var _data$offsets = data.offsets, popper = _data$offsets.popper, reference = _data$offsets.reference; var isVertical = ['left', 'right'].indexOf(placement) !== -1; var len = isVertical ? 'height' : 'width'; var sideCapitalized = isVertical ? 'Top' : 'Left'; var side = sideCapitalized.toLowerCase(); var altSide = isVertical ? 'left' : 'top'; var opSide = isVertical ? 'bottom' : 'right'; var arrowElementSize = getOuterSizes(arrowElement)[len]; // // extends keepTogether behavior making sure the popper and its // reference have enough pixels in conjunction // // top/left side if (reference[opSide] - arrowElementSize < popper[side]) { data.offsets.popper[side] -= popper[side] - (reference[opSide] - arrowElementSize); } // bottom/right side if (reference[side] + arrowElementSize > popper[opSide]) { data.offsets.popper[side] += reference[side] + arrowElementSize - popper[opSide]; } data.offsets.popper = getClientRect(data.offsets.popper); // compute center of the popper var center = reference[side] + reference[len] / 2 - arrowElementSize / 2; // Compute the sideValue using the updated popper offsets // take popper margin in account because we don't have this info available var css = getStyleComputedProperty(data.instance.popper); var popperMarginSide = parseFloat(css['margin' + sideCapitalized]); var popperBorderSide = parseFloat(css['border' + sideCapitalized + 'Width']); var sideValue = center - data.offsets.popper[side] - popperMarginSide - popperBorderSide; // prevent arrowElement from being placed not contiguously to its popper sideValue = Math.max(Math.min(popper[len] - arrowElementSize, sideValue), 0); data.arrowElement = arrowElement; data.offsets.arrow = (_data$offsets$arrow = {}, defineProperty(_data$offsets$arrow, side, Math.round(sideValue)), defineProperty(_data$offsets$arrow, altSide, ''), _data$offsets$arrow); return data; } /** * Get the opposite placement variation of the given one * @method * @memberof Popper.Utils * @argument {String} placement variation * @returns {String} flipped placement variation */ function getOppositeVariation(variation) { if (variation === 'end') { return 'start'; } else if (variation === 'start') { return 'end'; } return variation; } /** * List of accepted placements to use as values of the `placement` option.
* Valid placements are: * - `auto` * - `top` * - `right` * - `bottom` * - `left` * * Each placement can have a variation from this list: * - `-start` * - `-end` * * Variations are interpreted easily if you think of them as the left to right * written languages. Horizontally (`top` and `bottom`), `start` is left and `end` * is right.
* Vertically (`left` and `right`), `start` is top and `end` is bottom. * * Some valid examples are: * - `top-end` (on top of reference, right aligned) * - `right-start` (on right of reference, top aligned) * - `bottom` (on bottom, centered) * - `auto-end` (on the side with more space available, alignment depends by placement) * * @static * @type {Array} * @enum {String} * @readonly * @method placements * @memberof Popper */ var placements = ['auto-start', 'auto', 'auto-end', 'top-start', 'top', 'top-end', 'right-start', 'right', 'right-end', 'bottom-end', 'bottom', 'bottom-start', 'left-end', 'left', 'left-start']; // Get rid of `auto` `auto-start` and `auto-end` var validPlacements = placements.slice(3); /** * Given an initial placement, returns all the subsequent placements * clockwise (or counter-clockwise). * * @method * @memberof Popper.Utils * @argument {String} placement - A valid placement (it accepts variations) * @argument {Boolean} counter - Set to true to walk the placements counterclockwise * @returns {Array} placements including their variations */ function clockwise(placement) { var counter = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; var index = validPlacements.indexOf(placement); var arr = validPlacements.slice(index + 1).concat(validPlacements.slice(0, index)); return counter ? arr.reverse() : arr; } var BEHAVIORS = { FLIP: 'flip', CLOCKWISE: 'clockwise', COUNTERCLOCKWISE: 'counterclockwise' }; /** * @function * @memberof Modifiers * @argument {Object} data - The data object generated by update method * @argument {Object} options - Modifiers configuration and options * @returns {Object} The data object, properly modified */ function flip(data, options) { // if `inner` modifier is enabled, we can't use the `flip` modifier if (isModifierEnabled(data.instance.modifiers, 'inner')) { return data; } if (data.flipped && data.placement === data.originalPlacement) { // seems like flip is trying to loop, probably there's not enough space on any of the flippable sides return data; } var boundaries = getBoundaries(data.instance.popper, data.instance.reference, options.padding, options.boundariesElement, data.positionFixed); var placement = data.placement.split('-')[0]; var placementOpposite = getOppositePlacement(placement); var variation = data.placement.split('-')[1] || ''; var flipOrder = []; switch (options.behavior) { case BEHAVIORS.FLIP: flipOrder = [placement, placementOpposite]; break; case BEHAVIORS.CLOCKWISE: flipOrder = clockwise(placement); break; case BEHAVIORS.COUNTERCLOCKWISE: flipOrder = clockwise(placement, true); break; default: flipOrder = options.behavior; } flipOrder.forEach(function (step, index) { if (placement !== step || flipOrder.length === index + 1) { return data; } placement = data.placement.split('-')[0]; placementOpposite = getOppositePlacement(placement); var popperOffsets = data.offsets.popper; var refOffsets = data.offsets.reference; // using floor because the reference offsets may contain decimals we are not going to consider here var floor = Math.floor; var overlapsRef = placement === 'left' && floor(popperOffsets.right) > floor(refOffsets.left) || placement === 'right' && floor(popperOffsets.left) < floor(refOffsets.right) || placement === 'top' && floor(popperOffsets.bottom) > floor(refOffsets.top) || placement === 'bottom' && floor(popperOffsets.top) < floor(refOffsets.bottom); var overflowsLeft = floor(popperOffsets.left) < floor(boundaries.left); var overflowsRight = floor(popperOffsets.right) > floor(boundaries.right); var overflowsTop = floor(popperOffsets.top) < floor(boundaries.top); var overflowsBottom = floor(popperOffsets.bottom) > floor(boundaries.bottom); var overflowsBoundaries = placement === 'left' && overflowsLeft || placement === 'right' && overflowsRight || placement === 'top' && overflowsTop || placement === 'bottom' && overflowsBottom; // flip the variation if required var isVertical = ['top', 'bottom'].indexOf(placement) !== -1; // flips variation if reference element overflows boundaries var flippedVariationByRef = !!options.flipVariations && (isVertical && variation === 'start' && overflowsLeft || isVertical && variation === 'end' && overflowsRight || !isVertical && variation === 'start' && overflowsTop || !isVertical && variation === 'end' && overflowsBottom); // flips variation if popper content overflows boundaries var flippedVariationByContent = !!options.flipVariationsByContent && (isVertical && variation === 'start' && overflowsRight || isVertical && variation === 'end' && overflowsLeft || !isVertical && variation === 'start' && overflowsBottom || !isVertical && variation === 'end' && overflowsTop); var flippedVariation = flippedVariationByRef || flippedVariationByContent; if (overlapsRef || overflowsBoundaries || flippedVariation) { // this boolean to detect any flip loop data.flipped = true; if (overlapsRef || overflowsBoundaries) { placement = flipOrder[index + 1]; } if (flippedVariation) { variation = getOppositeVariation(variation); } data.placement = placement + (variation ? '-' + variation : ''); // this object contains `position`, we want to preserve it along with // any additional property we may add in the future data.offsets.popper = _extends({}, data.offsets.popper, getPopperOffsets(data.instance.popper, data.offsets.reference, data.placement)); data = runModifiers(data.instance.modifiers, data, 'flip'); } }); return data; } /** * @function * @memberof Modifiers * @argument {Object} data - The data object generated by update method * @argument {Object} options - Modifiers configuration and options * @returns {Object} The data object, properly modified */ function keepTogether(data) { var _data$offsets = data.offsets, popper = _data$offsets.popper, reference = _data$offsets.reference; var placement = data.placement.split('-')[0]; var floor = Math.floor; var isVertical = ['top', 'bottom'].indexOf(placement) !== -1; var side = isVertical ? 'right' : 'bottom'; var opSide = isVertical ? 'left' : 'top'; var measurement = isVertical ? 'width' : 'height'; if (popper[side] < floor(reference[opSide])) { data.offsets.popper[opSide] = floor(reference[opSide]) - popper[measurement]; } if (popper[opSide] > floor(reference[side])) { data.offsets.popper[opSide] = floor(reference[side]); } return data; } /** * Converts a string containing value + unit into a px value number * @function * @memberof {modifiers~offset} * @private * @argument {String} str - Value + unit string * @argument {String} measurement - `height` or `width` * @argument {Object} popperOffsets * @argument {Object} referenceOffsets * @returns {Number|String} * Value in pixels, or original string if no values were extracted */ function toValue(str, measurement, popperOffsets, referenceOffsets) { // separate value from unit var split = str.match(/((?:\-|\+)?\d*\.?\d*)(.*)/); var value = +split[1]; var unit = split[2]; // If it's not a number it's an operator, I guess if (!value) { return str; } if (unit.indexOf('%') === 0) { var element = void 0; switch (unit) { case '%p': element = popperOffsets; break; case '%': case '%r': default: element = referenceOffsets; } var rect = getClientRect(element); return rect[measurement] / 100 * value; } else if (unit === 'vh' || unit === 'vw') { // if is a vh or vw, we calculate the size based on the viewport var size = void 0; if (unit === 'vh') { size = Math.max(document.documentElement.clientHeight, window.innerHeight || 0); } else { size = Math.max(document.documentElement.clientWidth, window.innerWidth || 0); } return size / 100 * value; } else { // if is an explicit pixel unit, we get rid of the unit and keep the value // if is an implicit unit, it's px, and we return just the value return value; } } /** * Parse an `offset` string to extrapolate `x` and `y` numeric offsets. * @function * @memberof {modifiers~offset} * @private * @argument {String} offset * @argument {Object} popperOffsets * @argument {Object} referenceOffsets * @argument {String} basePlacement * @returns {Array} a two cells array with x and y offsets in numbers */ function parseOffset(offset, popperOffsets, referenceOffsets, basePlacement) { var offsets = [0, 0]; // Use height if placement is left or right and index is 0 otherwise use width // in this way the first offset will use an axis and the second one // will use the other one var useHeight = ['right', 'left'].indexOf(basePlacement) !== -1; // Split the offset string to obtain a list of values and operands // The regex addresses values with the plus or minus sign in front (+10, -20, etc) var fragments = offset.split(/(\+|\-)/).map(function (frag) { return frag.trim(); }); // Detect if the offset string contains a pair of values or a single one // they could be separated by comma or space var divider = fragments.indexOf(find(fragments, function (frag) { return frag.search(/,|\s/) !== -1; })); if (fragments[divider] && fragments[divider].indexOf(',') === -1) { console.warn('Offsets separated by white space(s) are deprecated, use a comma (,) instead.'); } // If divider is found, we divide the list of values and operands to divide // them by ofset X and Y. var splitRegex = /\s*,\s*|\s+/; var ops = divider !== -1 ? [fragments.slice(0, divider).concat([fragments[divider].split(splitRegex)[0]]), [fragments[divider].split(splitRegex)[1]].concat(fragments.slice(divider + 1))] : [fragments]; // Convert the values with units to absolute pixels to allow our computations ops = ops.map(function (op, index) { // Most of the units rely on the orientation of the popper var measurement = (index === 1 ? !useHeight : useHeight) ? 'height' : 'width'; var mergeWithPrevious = false; return op // This aggregates any `+` or `-` sign that aren't considered operators // e.g.: 10 + +5 => [10, +, +5] .reduce(function (a, b) { if (a[a.length - 1] === '' && ['+', '-'].indexOf(b) !== -1) { a[a.length - 1] = b; mergeWithPrevious = true; return a; } else if (mergeWithPrevious) { a[a.length - 1] += b; mergeWithPrevious = false; return a; } else { return a.concat(b); } }, []) // Here we convert the string values into number values (in px) .map(function (str) { return toValue(str, measurement, popperOffsets, referenceOffsets); }); }); // Loop trough the offsets arrays and execute the operations ops.forEach(function (op, index) { op.forEach(function (frag, index2) { if (isNumeric(frag)) { offsets[index] += frag * (op[index2 - 1] === '-' ? -1 : 1); } }); }); return offsets; } /** * @function * @memberof Modifiers * @argument {Object} data - The data object generated by update method * @argument {Object} options - Modifiers configuration and options * @argument {Number|String} options.offset=0 * The offset value as described in the modifier description * @returns {Object} The data object, properly modified */ function offset(data, _ref) { var offset = _ref.offset; var placement = data.placement, _data$offsets = data.offsets, popper = _data$offsets.popper, reference = _data$offsets.reference; var basePlacement = placement.split('-')[0]; var offsets = void 0; if (isNumeric(+offset)) { offsets = [+offset, 0]; } else { offsets = parseOffset(offset, popper, reference, basePlacement); } if (basePlacement === 'left') { popper.top += offsets[0]; popper.left -= offsets[1]; } else if (basePlacement === 'right') { popper.top += offsets[0]; popper.left += offsets[1]; } else if (basePlacement === 'top') { popper.left += offsets[0]; popper.top -= offsets[1]; } else if (basePlacement === 'bottom') { popper.left += offsets[0]; popper.top += offsets[1]; } data.popper = popper; return data; } /** * @function * @memberof Modifiers * @argument {Object} data - The data object generated by `update` method * @argument {Object} options - Modifiers configuration and options * @returns {Object} The data object, properly modified */ function preventOverflow(data, options) { var boundariesElement = options.boundariesElement || getOffsetParent(data.instance.popper); // If offsetParent is the reference element, we really want to // go one step up and use the next offsetParent as reference to // avoid to make this modifier completely useless and look like broken if (data.instance.reference === boundariesElement) { boundariesElement = getOffsetParent(boundariesElement); } // NOTE: DOM access here // resets the popper's position so that the document size can be calculated excluding // the size of the popper element itself var transformProp = getSupportedPropertyName('transform'); var popperStyles = data.instance.popper.style; // assignment to help minification var top = popperStyles.top, left = popperStyles.left, transform = popperStyles[transformProp]; popperStyles.top = ''; popperStyles.left = ''; popperStyles[transformProp] = ''; var boundaries = getBoundaries(data.instance.popper, data.instance.reference, options.padding, boundariesElement, data.positionFixed); // NOTE: DOM access here // restores the original style properties after the offsets have been computed popperStyles.top = top; popperStyles.left = left; popperStyles[transformProp] = transform; options.boundaries = boundaries; var order = options.priority; var popper = data.offsets.popper; var check = { primary: function primary(placement) { var value = popper[placement]; if (popper[placement] < boundaries[placement] && !options.escapeWithReference) { value = Math.max(popper[placement], boundaries[placement]); } return defineProperty({}, placement, value); }, secondary: function secondary(placement) { var mainSide = placement === 'right' ? 'left' : 'top'; var value = popper[mainSide]; if (popper[placement] > boundaries[placement] && !options.escapeWithReference) { value = Math.min(popper[mainSide], boundaries[placement] - (placement === 'right' ? popper.width : popper.height)); } return defineProperty({}, mainSide, value); } }; order.forEach(function (placement) { var side = ['left', 'top'].indexOf(placement) !== -1 ? 'primary' : 'secondary'; popper = _extends({}, popper, check[side](placement)); }); data.offsets.popper = popper; return data; } /** * @function * @memberof Modifiers * @argument {Object} data - The data object generated by `update` method * @argument {Object} options - Modifiers configuration and options * @returns {Object} The data object, properly modified */ function shift(data) { var placement = data.placement; var basePlacement = placement.split('-')[0]; var shiftvariation = placement.split('-')[1]; // if shift shiftvariation is specified, run the modifier if (shiftvariation) { var _data$offsets = data.offsets, reference = _data$offsets.reference, popper = _data$offsets.popper; var isVertical = ['bottom', 'top'].indexOf(basePlacement) !== -1; var side = isVertical ? 'left' : 'top'; var measurement = isVertical ? 'width' : 'height'; var shiftOffsets = { start: defineProperty({}, side, reference[side]), end: defineProperty({}, side, reference[side] + reference[measurement] - popper[measurement]) }; data.offsets.popper = _extends({}, popper, shiftOffsets[shiftvariation]); } return data; } /** * @function * @memberof Modifiers * @argument {Object} data - The data object generated by update method * @argument {Object} options - Modifiers configuration and options * @returns {Object} The data object, properly modified */ function hide(data) { if (!isModifierRequired(data.instance.modifiers, 'hide', 'preventOverflow')) { return data; } var refRect = data.offsets.reference; var bound = find(data.instance.modifiers, function (modifier) { return modifier.name === 'preventOverflow'; }).boundaries; if (refRect.bottom < bound.top || refRect.left > bound.right || refRect.top > bound.bottom || refRect.right < bound.left) { // Avoid unnecessary DOM access if visibility hasn't changed if (data.hide === true) { return data; } data.hide = true; data.attributes['x-out-of-boundaries'] = ''; } else { // Avoid unnecessary DOM access if visibility hasn't changed if (data.hide === false) { return data; } data.hide = false; data.attributes['x-out-of-boundaries'] = false; } return data; } /** * @function * @memberof Modifiers * @argument {Object} data - The data object generated by `update` method * @argument {Object} options - Modifiers configuration and options * @returns {Object} The data object, properly modified */ function inner(data) { var placement = data.placement; var basePlacement = placement.split('-')[0]; var _data$offsets = data.offsets, popper = _data$offsets.popper, reference = _data$offsets.reference; var isHoriz = ['left', 'right'].indexOf(basePlacement) !== -1; var subtractLength = ['top', 'left'].indexOf(basePlacement) === -1; popper[isHoriz ? 'left' : 'top'] = reference[basePlacement] - (subtractLength ? popper[isHoriz ? 'width' : 'height'] : 0); data.placement = getOppositePlacement(placement); data.offsets.popper = getClientRect(popper); return data; } /** * Modifier function, each modifier can have a function of this type assigned * to its `fn` property.
* These functions will be called on each update, this means that you must * make sure they are performant enough to avoid performance bottlenecks. * * @function ModifierFn * @argument {dataObject} data - The data object generated by `update` method * @argument {Object} options - Modifiers configuration and options * @returns {dataObject} The data object, properly modified */ /** * Modifiers are plugins used to alter the behavior of your poppers.
* Popper.js uses a set of 9 modifiers to provide all the basic functionalities * needed by the library. * * Usually you don't want to override the `order`, `fn` and `onLoad` props. * All the other properties are configurations that could be tweaked. * @namespace modifiers */ var modifiers = { /** * Modifier used to shift the popper on the start or end of its reference * element.
* It will read the variation of the `placement` property.
* It can be one either `-end` or `-start`. * @memberof modifiers * @inner */ shift: { /** @prop {number} order=100 - Index used to define the order of execution */ order: 100, /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */ enabled: true, /** @prop {ModifierFn} */ fn: shift }, /** * The `offset` modifier can shift your popper on both its axis. * * It accepts the following units: * - `px` or unit-less, interpreted as pixels * - `%` or `%r`, percentage relative to the length of the reference element * - `%p`, percentage relative to the length of the popper element * - `vw`, CSS viewport width unit * - `vh`, CSS viewport height unit * * For length is intended the main axis relative to the placement of the popper.
* This means that if the placement is `top` or `bottom`, the length will be the * `width`. In case of `left` or `right`, it will be the `height`. * * You can provide a single value (as `Number` or `String`), or a pair of values * as `String` divided by a comma or one (or more) white spaces.
* The latter is a deprecated method because it leads to confusion and will be * removed in v2.
* Additionally, it accepts additions and subtractions between different units. * Note that multiplications and divisions aren't supported. * * Valid examples are: * ``` * 10 * '10%' * '10, 10' * '10%, 10' * '10 + 10%' * '10 - 5vh + 3%' * '-10px + 5vh, 5px - 6%' * ``` * > **NB**: If you desire to apply offsets to your poppers in a way that may make them overlap * > with their reference element, unfortunately, you will have to disable the `flip` modifier. * > You can read more on this at this [issue](https://github.com/FezVrasta/popper.js/issues/373). * * @memberof modifiers * @inner */ offset: { /** @prop {number} order=200 - Index used to define the order of execution */ order: 200, /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */ enabled: true, /** @prop {ModifierFn} */ fn: offset, /** @prop {Number|String} offset=0 * The offset value as described in the modifier description */ offset: 0 }, /** * Modifier used to prevent the popper from being positioned outside the boundary. * * A scenario exists where the reference itself is not within the boundaries.
* We can say it has "escaped the boundaries" — or just "escaped".
* In this case we need to decide whether the popper should either: * * - detach from the reference and remain "trapped" in the boundaries, or * - if it should ignore the boundary and "escape with its reference" * * When `escapeWithReference` is set to`true` and reference is completely * outside its boundaries, the popper will overflow (or completely leave) * the boundaries in order to remain attached to the edge of the reference. * * @memberof modifiers * @inner */ preventOverflow: { /** @prop {number} order=300 - Index used to define the order of execution */ order: 300, /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */ enabled: true, /** @prop {ModifierFn} */ fn: preventOverflow, /** * @prop {Array} [priority=['left','right','top','bottom']] * Popper will try to prevent overflow following these priorities by default, * then, it could overflow on the left and on top of the `boundariesElement` */ priority: ['left', 'right', 'top', 'bottom'], /** * @prop {number} padding=5 * Amount of pixel used to define a minimum distance between the boundaries * and the popper. This makes sure the popper always has a little padding * between the edges of its container */ padding: 5, /** * @prop {String|HTMLElement} boundariesElement='scrollParent' * Boundaries used by the modifier. Can be `scrollParent`, `window`, * `viewport` or any DOM element. */ boundariesElement: 'scrollParent' }, /** * Modifier used to make sure the reference and its popper stay near each other * without leaving any gap between the two. Especially useful when the arrow is * enabled and you want to ensure that it points to its reference element. * It cares only about the first axis. You can still have poppers with margin * between the popper and its reference element. * @memberof modifiers * @inner */ keepTogether: { /** @prop {number} order=400 - Index used to define the order of execution */ order: 400, /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */ enabled: true, /** @prop {ModifierFn} */ fn: keepTogether }, /** * This modifier is used to move the `arrowElement` of the popper to make * sure it is positioned between the reference element and its popper element. * It will read the outer size of the `arrowElement` node to detect how many * pixels of conjunction are needed. * * It has no effect if no `arrowElement` is provided. * @memberof modifiers * @inner */ arrow: { /** @prop {number} order=500 - Index used to define the order of execution */ order: 500, /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */ enabled: true, /** @prop {ModifierFn} */ fn: arrow, /** @prop {String|HTMLElement} element='[x-arrow]' - Selector or node used as arrow */ element: '[x-arrow]' }, /** * Modifier used to flip the popper's placement when it starts to overlap its * reference element. * * Requires the `preventOverflow` modifier before it in order to work. * * **NOTE:** this modifier will interrupt the current update cycle and will * restart it if it detects the need to flip the placement. * @memberof modifiers * @inner */ flip: { /** @prop {number} order=600 - Index used to define the order of execution */ order: 600, /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */ enabled: true, /** @prop {ModifierFn} */ fn: flip, /** * @prop {String|Array} behavior='flip' * The behavior used to change the popper's placement. It can be one of * `flip`, `clockwise`, `counterclockwise` or an array with a list of valid * placements (with optional variations) */ behavior: 'flip', /** * @prop {number} padding=5 * The popper will flip if it hits the edges of the `boundariesElement` */ padding: 5, /** * @prop {String|HTMLElement} boundariesElement='viewport' * The element which will define the boundaries of the popper position. * The popper will never be placed outside of the defined boundaries * (except if `keepTogether` is enabled) */ boundariesElement: 'viewport', /** * @prop {Boolean} flipVariations=false * The popper will switch placement variation between `-start` and `-end` when * the reference element overlaps its boundaries. * * The original placement should have a set variation. */ flipVariations: false, /** * @prop {Boolean} flipVariationsByContent=false * The popper will switch placement variation between `-start` and `-end` when * the popper element overlaps its reference boundaries. * * The original placement should have a set variation. */ flipVariationsByContent: false }, /** * Modifier used to make the popper flow toward the inner of the reference element. * By default, when this modifier is disabled, the popper will be placed outside * the reference element. * @memberof modifiers * @inner */ inner: { /** @prop {number} order=700 - Index used to define the order of execution */ order: 700, /** @prop {Boolean} enabled=false - Whether the modifier is enabled or not */ enabled: false, /** @prop {ModifierFn} */ fn: inner }, /** * Modifier used to hide the popper when its reference element is outside of the * popper boundaries. It will set a `x-out-of-boundaries` attribute which can * be used to hide with a CSS selector the popper when its reference is * out of boundaries. * * Requires the `preventOverflow` modifier before it in order to work. * @memberof modifiers * @inner */ hide: { /** @prop {number} order=800 - Index used to define the order of execution */ order: 800, /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */ enabled: true, /** @prop {ModifierFn} */ fn: hide }, /** * Computes the style that will be applied to the popper element to gets * properly positioned. * * Note that this modifier will not touch the DOM, it just prepares the styles * so that `applyStyle` modifier can apply it. This separation is useful * in case you need to replace `applyStyle` with a custom implementation. * * This modifier has `850` as `order` value to maintain backward compatibility * with previous versions of Popper.js. Expect the modifiers ordering method * to change in future major versions of the library. * * @memberof modifiers * @inner */ computeStyle: { /** @prop {number} order=850 - Index used to define the order of execution */ order: 850, /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */ enabled: true, /** @prop {ModifierFn} */ fn: computeStyle, /** * @prop {Boolean} gpuAcceleration=true * If true, it uses the CSS 3D transformation to position the popper. * Otherwise, it will use the `top` and `left` properties */ gpuAcceleration: true, /** * @prop {string} [x='bottom'] * Where to anchor the X axis (`bottom` or `top`). AKA X offset origin. * Change this if your popper should grow in a direction different from `bottom` */ x: 'bottom', /** * @prop {string} [x='left'] * Where to anchor the Y axis (`left` or `right`). AKA Y offset origin. * Change this if your popper should grow in a direction different from `right` */ y: 'right' }, /** * Applies the computed styles to the popper element. * * All the DOM manipulations are limited to this modifier. This is useful in case * you want to integrate Popper.js inside a framework or view library and you * want to delegate all the DOM manipulations to it. * * Note that if you disable this modifier, you must make sure the popper element * has its position set to `absolute` before Popper.js can do its work! * * Just disable this modifier and define your own to achieve the desired effect. * * @memberof modifiers * @inner */ applyStyle: { /** @prop {number} order=900 - Index used to define the order of execution */ order: 900, /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */ enabled: true, /** @prop {ModifierFn} */ fn: applyStyle, /** @prop {Function} */ onLoad: applyStyleOnLoad, /** * @deprecated since version 1.10.0, the property moved to `computeStyle` modifier * @prop {Boolean} gpuAcceleration=true * If true, it uses the CSS 3D transformation to position the popper. * Otherwise, it will use the `top` and `left` properties */ gpuAcceleration: undefined } }; /** * The `dataObject` is an object containing all the information used by Popper.js. * This object is passed to modifiers and to the `onCreate` and `onUpdate` callbacks. * @name dataObject * @property {Object} data.instance The Popper.js instance * @property {String} data.placement Placement applied to popper * @property {String} data.originalPlacement Placement originally defined on init * @property {Boolean} data.flipped True if popper has been flipped by flip modifier * @property {Boolean} data.hide True if the reference element is out of boundaries, useful to know when to hide the popper * @property {HTMLElement} data.arrowElement Node used as arrow by arrow modifier * @property {Object} data.styles Any CSS property defined here will be applied to the popper. It expects the JavaScript nomenclature (eg. `marginBottom`) * @property {Object} data.arrowStyles Any CSS property defined here will be applied to the popper arrow. It expects the JavaScript nomenclature (eg. `marginBottom`) * @property {Object} data.boundaries Offsets of the popper boundaries * @property {Object} data.offsets The measurements of popper, reference and arrow elements * @property {Object} data.offsets.popper `top`, `left`, `width`, `height` values * @property {Object} data.offsets.reference `top`, `left`, `width`, `height` values * @property {Object} data.offsets.arrow] `top` and `left` offsets, only one of them will be different from 0 */ /** * Default options provided to Popper.js constructor.
* These can be overridden using the `options` argument of Popper.js.
* To override an option, simply pass an object with the same * structure of the `options` object, as the 3rd argument. For example: * ``` * new Popper(ref, pop, { * modifiers: { * preventOverflow: { enabled: false } * } * }) * ``` * @type {Object} * @static * @memberof Popper */ var Defaults = { /** * Popper's placement. * @prop {Popper.placements} placement='bottom' */ placement: 'bottom', /** * Set this to true if you want popper to position it self in 'fixed' mode * @prop {Boolean} positionFixed=false */ positionFixed: false, /** * Whether events (resize, scroll) are initially enabled. * @prop {Boolean} eventsEnabled=true */ eventsEnabled: true, /** * Set to true if you want to automatically remove the popper when * you call the `destroy` method. * @prop {Boolean} removeOnDestroy=false */ removeOnDestroy: false, /** * Callback called when the popper is created.
* By default, it is set to no-op.
* Access Popper.js instance with `data.instance`. * @prop {onCreate} */ onCreate: function onCreate() {}, /** * Callback called when the popper is updated. This callback is not called * on the initialization/creation of the popper, but only on subsequent * updates.
* By default, it is set to no-op.
* Access Popper.js instance with `data.instance`. * @prop {onUpdate} */ onUpdate: function onUpdate() {}, /** * List of modifiers used to modify the offsets before they are applied to the popper. * They provide most of the functionalities of Popper.js. * @prop {modifiers} */ modifiers: modifiers }; /** * @callback onCreate * @param {dataObject} data */ /** * @callback onUpdate * @param {dataObject} data */ // Utils // Methods var Popper = function () { /** * Creates a new Popper.js instance. * @class Popper * @param {Element|referenceObject} reference - The reference element used to position the popper * @param {Element} popper - The HTML / XML element used as the popper * @param {Object} options - Your custom options to override the ones defined in [Defaults](#defaults) * @return {Object} instance - The generated Popper.js instance */ function Popper(reference, popper) { var _this = this; var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; classCallCheck(this, Popper); this.scheduleUpdate = function () { return requestAnimationFrame(_this.update); }; // make update() debounced, so that it only runs at most once-per-tick this.update = debounce(this.update.bind(this)); // with {} we create a new object with the options inside it this.options = _extends({}, Popper.Defaults, options); // init state this.state = { isDestroyed: false, isCreated: false, scrollParents: [] }; // get reference and popper elements (allow jQuery wrappers) this.reference = reference && reference.jquery ? reference[0] : reference; this.popper = popper && popper.jquery ? popper[0] : popper; // Deep merge modifiers options this.options.modifiers = {}; Object.keys(_extends({}, Popper.Defaults.modifiers, options.modifiers)).forEach(function (name) { _this.options.modifiers[name] = _extends({}, Popper.Defaults.modifiers[name] || {}, options.modifiers ? options.modifiers[name] : {}); }); // Refactoring modifiers' list (Object => Array) this.modifiers = Object.keys(this.options.modifiers).map(function (name) { return _extends({ name: name }, _this.options.modifiers[name]); }) // sort the modifiers by order .sort(function (a, b) { return a.order - b.order; }); // modifiers have the ability to execute arbitrary code when Popper.js get inited // such code is executed in the same order of its modifier // they could add new properties to their options configuration // BE AWARE: don't add options to `options.modifiers.name` but to `modifierOptions`! this.modifiers.forEach(function (modifierOptions) { if (modifierOptions.enabled && isFunction(modifierOptions.onLoad)) { modifierOptions.onLoad(_this.reference, _this.popper, _this.options, modifierOptions, _this.state); } }); // fire the first update to position the popper in the right place this.update(); var eventsEnabled = this.options.eventsEnabled; if (eventsEnabled) { // setup event listeners, they will take care of update the position in specific situations this.enableEventListeners(); } this.state.eventsEnabled = eventsEnabled; } // We can't use class properties because they don't get listed in the // class prototype and break stuff like Sinon stubs createClass(Popper, [{ key: 'update', value: function update$$1() { return update.call(this); } }, { key: 'destroy', value: function destroy$$1() { return destroy.call(this); } }, { key: 'enableEventListeners', value: function enableEventListeners$$1() { return enableEventListeners.call(this); } }, { key: 'disableEventListeners', value: function disableEventListeners$$1() { return disableEventListeners.call(this); } /** * Schedules an update. It will run on the next UI update available. * @method scheduleUpdate * @memberof Popper */ /** * Collection of utilities useful when writing custom modifiers. * Starting from version 1.7, this method is available only if you * include `popper-utils.js` before `popper.js`. * * **DEPRECATION**: This way to access PopperUtils is deprecated * and will be removed in v2! Use the PopperUtils module directly instead. * Due to the high instability of the methods contained in Utils, we can't * guarantee them to follow semver. Use them at your own risk! * @static * @private * @type {Object} * @deprecated since version 1.8 * @member Utils * @memberof Popper */ }]); return Popper; }(); /** * The `referenceObject` is an object that provides an interface compatible with Popper.js * and lets you use it as replacement of a real DOM node.
* You can use this method to position a popper relatively to a set of coordinates * in case you don't have a DOM node to use as reference. * * ``` * new Popper(referenceObject, popperNode); * ``` * * NB: This feature isn't supported in Internet Explorer 10. * @name referenceObject * @property {Function} data.getBoundingClientRect * A function that returns a set of coordinates compatible with the native `getBoundingClientRect` method. * @property {number} data.clientWidth * An ES6 getter that will return the width of the virtual reference element. * @property {number} data.clientHeight * An ES6 getter that will return the height of the virtual reference element. */ Popper.Utils = (typeof window !== 'undefined' ? window : global).PopperUtils; Popper.placements = placements; Popper.Defaults = Defaults; /* harmony default export */ __webpack_exports__["a"] = (Popper); //# sourceMappingURL=popper.js.map /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(33))) /***/ }), /* 72 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* WEBPACK VAR INJECTION */(function(Hammer) {/* * picasso-plugin-hammer v0.27.1 * Copyright (c) 2019 QlikTech International AB * Released under the MIT license. */ /* global Hammer */ var translateKnownTypes = { click: 'Tap', Click: 'Tap', tap: 'Tap', pan: 'Pan', swipe: 'Swipe', rotate: 'Rotate', press: 'Press', pinch: 'Pinch' }; /** * Helper function for translating typical non-hammer gesture to a hammer gesture. Currently only supporting 'click' * @param {String} type Gesture type * @private */ function getGestureType(type) { return translateKnownTypes[type] || type; } /** * Manages event handlers for HammerJS. Assumes Hammer is loaded and added to the global namespace */ function hammer(chart, mediator, element) { var settings; var instance; var mc; var key; var hammerGestures = []; var isOn = true; /** * Set default settings * @private */ function setDefaultSettings(newSettings) { key = newSettings.key; //eslint-disable-line settings = newSettings; instance = { chart: chart, mediator: mediator, settings: settings }; settings.gestures = settings.gestures || []; if (settings.enable === undefined) { settings.enable = true; } } /** * @private * add hammer recognizers based on settings */ function addRecognizers() { if (typeof settings.enable === 'function') { settings.enable = settings.enable.bind(instance)(); } if (!settings.enable) { return; // interaction is disabled } settings.gestures.forEach(function (gesture) { gesture.options = gesture.options || {}; // handle action enable if (gesture.options.enable === undefined) { gesture.options.enable = true; } if (typeof gesture.options.enable === 'function') { gesture.options.enable = gesture.options.enable.bind(instance); } // setup hammer gestures var type = getGestureType(gesture.type); if (Hammer && Hammer[type]) { gesture.options.event = gesture.options.event || gesture.type.toLowerCase(); mc = mc || new Hammer.Manager(element); mc.add(new Hammer[type](gesture.options)); Object.keys(gesture.events).forEach(function (eventName) { gesture.events[eventName] = gesture.events[eventName].bind(instance); mc.on(eventName, gesture.events[eventName]); }); hammerGestures.push(gesture); } }); // setup mixing hammer gestures settings.gestures.forEach(function (gesture) { var type = getGestureType(gesture.type); if (Hammer && Hammer[type]) { if (gesture.recognizeWith) { mc.get(gesture.options.event).recognizeWith(gesture.recognizeWith.split(' ').filter(function (e) { return e !== ''; })); } if (gesture.requireFailure) { mc.get(gesture.options.event).requireFailure(gesture.requireFailure.split(' ').filter(function (e) { return e !== ''; })); } } }); } /** * @private * removes all added hammer recognizers and native events */ function removeAddedEvents() { // remove hammer recognizers and registered events hammerGestures.forEach(function (gesture) { Object.keys(gesture.events).forEach(function (eventName) { mc.off(eventName, gesture.events[eventName]); }); mc.remove(gesture.options.event); }); hammerGestures = []; } return { /** * Getter for the key. */ get key() { return key; }, /** * Updates this with new settings * @typedef settings * @type {object} * @property {string} [type] - The interaction type. Is 'hammer' for this component * @property {boolean|function} [enable] - Should the interaction be enabled or not. * This is only run when adding event handlers. In effect at startup, update or during on/off. * It does not run during every event loop. * @property {object} [events] - The keys in this object is the names of native events * that should be added to the chart element and they should all point to function which * will be the corresponding event handler. */ set: function set(newSettings) { setDefaultSettings(newSettings); removeAddedEvents(); if (isOn) { addRecognizers(); } }, /** * Turns off interactions */ off: function off() { isOn = false; removeAddedEvents(); }, /** * Turns off interactions */ on: function on() { isOn = true; if (hammerGestures.length === 0) { addRecognizers(); } }, /** * Destroys and unbinds all event handlers */ destroy: function destroy() { removeAddedEvents(); if (mc) { mc.destroy(); } mc = null; instance = null; settings = null; } }; } function initialize(picasso) { picasso.interaction('hammer', hammer); } /* harmony default export */ __webpack_exports__["a"] = (initialize); //# sourceMappingURL=picasso-hammer.esm.js.map /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(64))) /***/ }), /* 73 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* WEBPACK VAR INJECTION */(function(global) {/* * picasso-plugin-q v0.27.1 * Copyright (c) 2019 QlikTech International AB * Released under the MIT license. */ function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function (obj) { return typeof obj; }; } else { _typeof = function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } function _objectSpread2(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _construct(Parent, args, Class) { if (isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); } function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; return arr2; } } function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } function _iterableToArrayLimit(arr, i) { if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === "[object Arguments]")) { return; } var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } var hasOwn = Object.prototype.hasOwnProperty; var toStr = Object.prototype.toString; var defineProperty = Object.defineProperty; var gOPD = Object.getOwnPropertyDescriptor; var isArray = function isArray(arr) { if (typeof Array.isArray === 'function') { return Array.isArray(arr); } return toStr.call(arr) === '[object Array]'; }; var isPlainObject = function isPlainObject(obj) { if (!obj || toStr.call(obj) !== '[object Object]') { return false; } var hasOwnConstructor = hasOwn.call(obj, 'constructor'); var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf'); // Not own constructor property must be Object if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) { return false; } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. var key; for (key in obj) { /**/ } return typeof key === 'undefined' || hasOwn.call(obj, key); }; // If name is '__proto__', and Object.defineProperty is available, define __proto__ as an own property on target var setProperty = function setProperty(target, options) { if (defineProperty && options.name === '__proto__') { defineProperty(target, options.name, { enumerable: true, configurable: true, value: options.newValue, writable: true }); } else { target[options.name] = options.newValue; } }; // Return undefined instead of __proto__ if '__proto__' is not an own property var getProperty = function getProperty(obj, name) { if (name === '__proto__') { if (!hasOwn.call(obj, name)) { return void 0; } else if (gOPD) { // In early versions of node, obj['__proto__'] is buggy when obj has // __proto__ as an own property. Object.getOwnPropertyDescriptor() works. return gOPD(obj, name).value; } } return obj[name]; }; var extend = function extend() { var options, name, src, copy, copyIsArray, clone; var target = arguments[0]; var i = 1; var length = arguments.length; var deep = false; // Handle a deep copy situation if (typeof target === 'boolean') { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } if (target == null || (typeof target !== 'object' && typeof target !== 'function')) { target = {}; } for (; i < length; ++i) { options = arguments[i]; // Only deal with non-null/undefined values if (options != null) { // Extend the base object for (name in options) { src = getProperty(target, name); copy = getProperty(options, name); // Prevent never-ending loop if (target !== copy) { // Recurse if we're merging plain objects or arrays if (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) { if (copyIsArray) { copyIsArray = false; clone = src && isArray(src) ? src : []; } else { clone = src && isPlainObject(src) ? src : {}; } // Never move original objects, clone them setProperty(target, { name: name, newValue: extend(deep, clone, copy) }); // Don't bring in undefined values } else if (typeof copy !== 'undefined') { setProperty(target, { name: name, newValue: copy }); } } } } } // Return the modified object return target; }; function getFieldAccessor(field, page, deps) { if (!field) { return -1; } var cache = deps.cache; var origin = field.origin ? field.origin() : null; if (origin) { field = origin; } var fieldIdx = cache.fields.indexOf(field); var attrIdx = -1; var attrDimIdx = -1; if (fieldIdx === -1) { for (var i = 0; i < cache.wrappedFields.length; i++) { attrDimIdx = cache.wrappedFields[i].attrDims.map(function (v) { return v.instance; }).indexOf(field); attrIdx = cache.wrappedFields[i].attrExps.map(function (v) { return v.instance; }).indexOf(field); if (attrDimIdx !== -1 || attrIdx !== -1) { fieldIdx = i; break; } } } fieldIdx -= page.qArea.qLeft; if (fieldIdx < 0 || fieldIdx >= page.qArea.qWidth) { // throw new Error('Field out of range'); return -1; } if (attrDimIdx >= 0) { return function (row) { return row[fieldIdx].qAttrDims.qValues[attrDimIdx]; }; } if (attrIdx >= 0) { return function (row) { return row[fieldIdx].qAttrExps.qValues[attrIdx]; }; } return function (row) { return row[fieldIdx]; }; } // TODO - handle 'other' value // const specialTextValues = { // '-3': (meta) => { // if ('othersLabel' in meta) { // return meta.othersLabel; // } // return ''; // } // }; function datumExtract(propCfg, cell, _ref) { var key = _ref.key; var datum = { value: typeof propCfg.value === 'function' ? propCfg.value(cell) : typeof propCfg.value !== 'undefined' ? propCfg.value : cell // eslint-disable-line no-nested-ternary }; datum.label = typeof propCfg.label === 'function' ? propCfg.label(cell) : typeof propCfg.label !== 'undefined' ? String(propCfg.label) : String(datum.value); // eslint-disable-line no-nested-ternary if (propCfg.field) { datum.source = { key: key, field: propCfg.field.key() }; } return datum; } function cellToValue(_ref2) { var cache = _ref2.cache, f = _ref2.f, mainCell = _ref2.mainCell, p = _ref2.p, prop = _ref2.prop, page = _ref2.page, rowIdx = _ref2.rowIdx, row = _ref2.row, sourceKey = _ref2.sourceKey, target = _ref2.target, targetProp = _ref2.targetProp; var propCell = mainCell; if (p.field && p.field !== f) { var propCellFn = getFieldAccessor(p.field, page, { cache: cache }); if (propCellFn === -1) { return; } propCell = extend({ qRow: rowIdx }, propCellFn(row)); } target[targetProp] = datumExtract(p, propCell, { key: sourceKey }); } function extract(config, dataset, cache, util) { var cfgs = Array.isArray(config) ? config : [config]; var dataItems = []; for (var i = 0; i < cfgs.length; i++) { if (typeof cfgs[i].field !== 'undefined') { var cube = dataset.raw(); var sourceKey = dataset.key(); var f = _typeof(cfgs[i].field) === 'object' ? cfgs[i].field : dataset.field(cfgs[i].field); var _util$normalizeConfig = util.normalizeConfig(cfgs[i], dataset), props = _util$normalizeConfig.props, main = _util$normalizeConfig.main; var propsArr = Object.keys(props); var track = !!cfgs[i].trackBy; var trackType = _typeof(cfgs[i].trackBy); var tracker = {}; var trackedItems = []; var items = []; for (var j = 0; j < cube.qDataPages.length; j++) { var fn = getFieldAccessor(f, cube.qDataPages[j], { cache: cache }); if (fn === -1) { continue; } for (var k = 0; k < cube.qDataPages[j].qMatrix.length; k++) { var rowIdx = cube.qDataPages[j].qArea.qTop + k; var mainCell = extend({ qRow: rowIdx }, fn(cube.qDataPages[j].qMatrix[k])); var ret = datumExtract(main, mainCell, { key: sourceKey }); var exclude = main.filter && !main.filter(mainCell); if (exclude) { continue; } for (var l = 0; l < propsArr.length; l++) { var p = props[propsArr[l]]; var arr = p.fields || [p]; if (p.fields) { ret[propsArr[l]] = []; } // loop through all props that need to be mapped and // assign 'value' and 'source' to each property for (var m = 0; m < arr.length; m++) { cellToValue({ cache: cache, f: f, mainCell: mainCell, p: arr[m], prop: propsArr[l], props: props, page: cube.qDataPages[j], rowIdx: rowIdx, row: cube.qDataPages[j].qMatrix[k], sourceKey: sourceKey, target: p.fields ? ret[propsArr[l]] : ret, targetProp: p.fields ? m : propsArr[l] }); } if (p.fields) { var fieldValues = ret[propsArr[l]].map(function (v) { return v.value; }); var fieldLabels = ret[propsArr[l]].map(function (v) { return v.label; }); ret[propsArr[l]] = { value: typeof p.value === 'function' ? p.value(fieldValues) : typeof p.value !== 'undefined' ? p.value : fieldValues, label: typeof p.label === 'function' ? p.label(fieldLabels) : typeof p.label !== 'undefined' ? String(p.label) : String(ret[propsArr[l]].value) }; } } // collect items based on the trackBy value // items with the same trackBy value are placed in an array and reduced later if (track) { util.track({ cfg: cfgs[i], itemData: mainCell, obj: ret, target: trackedItems, tracker: tracker, trackType: trackType }); } items.push(ret); } } // reduce if items have been grouped if (track) { dataItems.push.apply(dataItems, _toConsumableArray(util.collect(trackedItems, { main: main, propsArr: propsArr, props: props }))); } else { dataItems.push.apply(dataItems, items); } } } return dataItems; } function count(node) { var sum = 0, children = node.children, i = children && children.length; if (!i) sum = 1; else while (--i >= 0) sum += children[i].value; node.value = sum; } function node_count() { return this.eachAfter(count); } function node_each(callback) { var node = this, current, next = [node], children, i, n; do { current = next.reverse(), next = []; while (node = current.pop()) { callback(node), children = node.children; if (children) for (i = 0, n = children.length; i < n; ++i) { next.push(children[i]); } } } while (next.length); return this; } function node_eachBefore(callback) { var node = this, nodes = [node], children, i; while (node = nodes.pop()) { callback(node), children = node.children; if (children) for (i = children.length - 1; i >= 0; --i) { nodes.push(children[i]); } } return this; } function node_eachAfter(callback) { var node = this, nodes = [node], next = [], children, i, n; while (node = nodes.pop()) { next.push(node), children = node.children; if (children) for (i = 0, n = children.length; i < n; ++i) { nodes.push(children[i]); } } while (node = next.pop()) { callback(node); } return this; } function node_sum(value) { return this.eachAfter(function(node) { var sum = +value(node.data) || 0, children = node.children, i = children && children.length; while (--i >= 0) sum += children[i].value; node.value = sum; }); } function node_sort(compare) { return this.eachBefore(function(node) { if (node.children) { node.children.sort(compare); } }); } function node_path(end) { var start = this, ancestor = leastCommonAncestor(start, end), nodes = [start]; while (start !== ancestor) { start = start.parent; nodes.push(start); } var k = nodes.length; while (end !== ancestor) { nodes.splice(k, 0, end); end = end.parent; } return nodes; } function leastCommonAncestor(a, b) { if (a === b) return a; var aNodes = a.ancestors(), bNodes = b.ancestors(), c = null; a = aNodes.pop(); b = bNodes.pop(); while (a === b) { c = a; a = aNodes.pop(); b = bNodes.pop(); } return c; } function node_ancestors() { var node = this, nodes = [node]; while (node = node.parent) { nodes.push(node); } return nodes; } function node_descendants() { var nodes = []; this.each(function(node) { nodes.push(node); }); return nodes; } function node_leaves() { var leaves = []; this.eachBefore(function(node) { if (!node.children) { leaves.push(node); } }); return leaves; } function node_links() { var root = this, links = []; root.each(function(node) { if (node !== root) { // Don’t include the root’s parent, if any. links.push({source: node.parent, target: node}); } }); return links; } function hierarchy(data, children) { var root = new Node(data), valued = +data.value && (root.value = data.value), node, nodes = [root], child, childs, i, n; if (children == null) children = defaultChildren; while (node = nodes.pop()) { if (valued) node.value = +node.data.value; if ((childs = children(node.data)) && (n = childs.length)) { node.children = new Array(n); for (i = n - 1; i >= 0; --i) { nodes.push(child = node.children[i] = new Node(childs[i])); child.parent = node; child.depth = node.depth + 1; } } } return root.eachBefore(computeHeight); } function node_copy() { return hierarchy(this).eachBefore(copyData); } function defaultChildren(d) { return d.children; } function copyData(node) { node.data = node.data.data; } function computeHeight(node) { var height = 0; do node.height = height; while ((node = node.parent) && (node.height < ++height)); } function Node(data) { this.data = data; this.depth = this.height = 0; this.parent = null; } Node.prototype = hierarchy.prototype = { constructor: Node, count: node_count, each: node_each, eachAfter: node_eachAfter, eachBefore: node_eachBefore, sum: node_sum, sort: node_sort, path: node_path, ancestors: node_ancestors, descendants: node_descendants, leaves: node_leaves, links: node_links, copy: node_copy }; function required(f) { if (typeof f !== "function") throw new Error; return f; } var keyPrefix = "$", // Protect against keys like “__proto__”. preroot = {depth: -1}, ambiguous = {}; function defaultId(d) { return d.id; } function defaultParentId(d) { return d.parentId; } function stratify() { var id = defaultId, parentId = defaultParentId; function stratify(data) { var d, i, n = data.length, root, parent, node, nodes = new Array(n), nodeId, nodeKey, nodeByKey = {}; for (i = 0; i < n; ++i) { d = data[i], node = nodes[i] = new Node(d); if ((nodeId = id(d, i, data)) != null && (nodeId += "")) { nodeKey = keyPrefix + (node.id = nodeId); nodeByKey[nodeKey] = nodeKey in nodeByKey ? ambiguous : node; } } for (i = 0; i < n; ++i) { node = nodes[i], nodeId = parentId(data[i], i, data); if (nodeId == null || !(nodeId += "")) { if (root) throw new Error("multiple roots"); root = node; } else { parent = nodeByKey[keyPrefix + nodeId]; if (!parent) throw new Error("missing: " + nodeId); if (parent === ambiguous) throw new Error("ambiguous: " + nodeId); if (parent.children) parent.children.push(node); else parent.children = [node]; node.parent = parent; } } if (!root) throw new Error("no root"); root.parent = preroot; root.eachBefore(function(node) { node.depth = node.parent.depth + 1; --n; }).eachBefore(computeHeight); root.parent = null; if (n > 0) throw new Error("cycle"); return root; } stratify.id = function(x) { return arguments.length ? (id = required(x), stratify) : id; }; stratify.parentId = function(x) { return arguments.length ? (parentId = required(x), stratify) : parentId; }; return stratify; } /** * Resolves the value at the given JSON path * @private * @param {String} path [description] * @param {Object} obj [description] * @return {Object} [description] * * @example * let path = "/path/to/paradise"; * let obj = { * path: { * to: { paradise: "heaven"}, * from: {...} * } * }; * resolve( path, obj ); // "heaven" */ function resolve(path, obj) { if (path.charAt(0) === '/') { path = path.substring(1); } var arr = path.split('/'); var subpath; var container = obj; for (var i = 0; i < arr.length; i++) { if (arr[i] === '*' && Array.isArray(container)) { var carr = []; subpath = arr.slice(i + 1).join('/'); for (var c = 0; c < container.length; c++) { var v = resolve(subpath, container[c]); // v.forEach(_ => _._parent = container[c]); if (Array.isArray(v)) { carr.push.apply(carr, _toConsumableArray(v)); } else { carr.push(v); } } return carr; // return container.map(v => resolve(arr.slice(i + 1).join('/'), v)); } if (!arr[i] && Array.isArray(container)) { var _carr = new Array(container.length); subpath = arr.slice(i + 1).join('/'); for (var _c = 0; _c < container.length; _c++) { _carr[_c] = resolve(subpath, container[_c]); } return _carr; // return container.map(v => resolve(arr.slice(i + 1).join('/'), v)); } if (arr[i] in container) { container = container[arr[i]]; } } return container; } function flattenTree(children, steps, arrIndexAtTargetDepth) { var arr = []; if (!children || !children.length) { return arr; } if (steps <= 0) { var nodes = arrIndexAtTargetDepth >= 0 ? [children[arrIndexAtTargetDepth]] : children; arr.push.apply(arr, _toConsumableArray(nodes)); } else { for (var i = 0; i < children.length; i++) { if (children[i].children && children[i].children.length) { arr.push.apply(arr, _toConsumableArray(flattenTree(children[i].children, steps - 1, arrIndexAtTargetDepth))); } } } return arr; } function treeAccessor(sourceDepth, targetDepth, arrIndexAtTargetDepth) { if (sourceDepth === targetDepth) { return function (d) { return d; }; } if (sourceDepth > targetDepth) { // traverse upwards var steps = Math.max(0, Math.min(100, sourceDepth - targetDepth)); var path = _toConsumableArray(Array(steps)).map(String.prototype.valueOf, 'parent').join('.'); return Function('node', "return node.".concat(path, ";")); // eslint-disable-line no-new-func } if (targetDepth > sourceDepth) { // flatten descendants var _steps = Math.max(0, Math.min(100, targetDepth - sourceDepth)); return function (node) { return flattenTree(node.children, _steps - 1, arrIndexAtTargetDepth); }; } return false; } function findField(query, _ref) { var cache = _ref.cache; if (typeof query === 'number') { return cache.fields[query]; } var allFields = cache.allFields; if (typeof query === 'function') { for (var i = 0; i < allFields.length; i++) { if (query(allFields[i])) { return allFields[i]; } } return false; } if (typeof query === 'string') { for (var _i = 0; _i < allFields.length; _i++) { if (allFields[_i].key() === query || allFields[_i].title() === query) { return allFields[_i]; } } } else if (query && allFields.indexOf(query) !== -1) { // assume 'query' is a field instance return query; } throw Error("Field not found: ".concat(query)); } var DIM_RX = /^qDimensionInfo(?:\/(\d+))?/; var M_RX = /^\/?qMeasureInfo\/(\d+)/; var ATTR_EXPR_RX = /\/qAttrExprInfo\/(\d+)/; var ATTR_DIM_RX = /\/qAttrDimInfo\/(\d+)/; function getColumnOrder(dataset) { var qColumnOrder = dataset.raw().qColumnOrder; var fields = dataset.fields(); return qColumnOrder && qColumnOrder.length === fields.length ? qColumnOrder : fields.map(function (f, i) { return i; }); } function getDimensionColumnOrder(cube) { var order = cube.qColumnOrder && cube.qColumnOrder.length ? cube.qColumnOrder : cube.qDimensionInfo.map(function (d, ii) { return ii; }); return order.filter(function (ii) { return ii < cube.qDimensionInfo.length; }); } function getFieldDepth(field, _ref) { var cube = _ref.cube; if (!field) { return -1; } var key = field.origin && field.origin() ? field.origin().key() : field.key(); var isFieldDimension = false; var fieldIdx = -1; // cache.fields.indexOf(field); var attrIdx = -1; var attrDimIdx = -1; var fieldDepth = -1; var pseudoMeasureIndex = -1; var measureIdx = -1; var remainder = key; var treeOrder = cube.qEffectiveInterColumnSortOrder; var columnOrder = getDimensionColumnOrder(cube); if (DIM_RX.test(remainder)) { isFieldDimension = true; fieldIdx = +DIM_RX.exec(remainder)[1]; remainder = key.replace(DIM_RX, ''); } if (M_RX.test(remainder)) { if (cube.qMode === 'K') { pseudoMeasureIndex = +M_RX.exec(remainder)[1]; } else if (treeOrder && treeOrder.indexOf(-1) !== -1) { pseudoMeasureIndex = +M_RX.exec(remainder)[1]; measureIdx = 0; } else { measureIdx = +M_RX.exec(remainder)[1]; } remainder = remainder.replace(M_RX, ''); } if (remainder) { if (ATTR_DIM_RX.exec(remainder)) { attrDimIdx = +ATTR_DIM_RX.exec(remainder)[1]; } else if (ATTR_EXPR_RX.exec(remainder)) { attrIdx = +ATTR_EXPR_RX.exec(remainder)[1]; } } if (isFieldDimension) { if (cube.qMode === 'S') { fieldDepth = columnOrder[fieldIdx]; } else { fieldDepth = treeOrder ? treeOrder.indexOf(fieldIdx) : fieldIdx; } } else if (treeOrder && treeOrder.indexOf(-1) !== -1) { // if pseudo dimension exists in sort order fieldDepth = treeOrder.indexOf(-1); // depth of pesudodimension } else { // assume measure is at the bottom of the tree fieldDepth = cube.qDimensionInfo.length - (cube.qMode === 'K' ? 0 : 1); } return { fieldDepth: fieldDepth + 1, // +1 due to root node pseudoMeasureIndex: pseudoMeasureIndex, measureIdx: measureIdx, attrDimIdx: attrDimIdx, attrIdx: attrIdx }; } function getFieldAccessor$1(sourceDepthObject, targetDepthObject) { var nodeFn = treeAccessor(sourceDepthObject.fieldDepth, targetDepthObject.fieldDepth, targetDepthObject.pseudoMeasureIndex); var valueFn; if (targetDepthObject.measureIdx >= 0) { valueFn = function valueFn(node) { return node.data.qValues[targetDepthObject.measureIdx]; }; } else { valueFn = function valueFn(node) { return node.data; }; } var attrFn; if (targetDepthObject.attrDimIdx >= 0) { attrFn = function attrFn(data) { return data.qAttrDims.qValues[targetDepthObject.attrDimIdx]; }; } else if (targetDepthObject.attrIdx >= 0) { attrFn = function attrFn(data) { return data.qAttrExps.qValues[targetDepthObject.attrIdx]; }; } return { nodeFn: nodeFn, attrFn: attrFn, valueFn: valueFn }; } function datumExtract$1(propCfg, cell, _ref2) { var key = _ref2.key; var datum = { value: typeof propCfg.value === 'function' ? propCfg.value(cell) : typeof propCfg.value !== 'undefined' ? propCfg.value : cell // eslint-disable-line no-nested-ternary }; datum.label = typeof propCfg.label === 'function' ? propCfg.label(cell) : typeof propCfg.label !== 'undefined' ? String(propCfg.label) : String(datum.value); // eslint-disable-line no-nested-ternary if (propCfg.field) { datum.source = { key: key, field: propCfg.field.key() }; } return datum; } function doIt(_ref3) { var propsArr = _ref3.propsArr, props = _ref3.props, item = _ref3.item, itemData = _ref3.itemData, ret = _ref3.ret, sourceKey = _ref3.sourceKey; for (var i = 0; i < propsArr.length; i++) { var pCfg = props[propsArr[i]]; var arr = pCfg.fields || [pCfg]; var coll = void 0; var collStr = void 0; if (pCfg.fields) { coll = []; collStr = []; } var _loop = function _loop(j) { var p = arr[j]; var fn = void 0; var str = void 0; var value = void 0; var nodes = void 0; var cells = void 0; var label = void 0; if (p.type === 'primitive') { value = p.value; label = String(p.value); } else { if (typeof p.value === 'function') { fn = function fn(v) { return p.value(v, item); }; } if (typeof p.label === 'function') { str = function str(v) { return p.label(v, item); }; } if (p.accessor) { nodes = p.accessor(item); if (Array.isArray(nodes)) { // propably descendants cells = nodes.map(p.valueAccessor); if (p.attrAccessor) { cells = cells.map(p.attrAccessor); } if (fn) { value = cells.map(fn); fn = null; } if (str) { label = cells.map(str); str = null; } value = p.reduce ? p.reduce(value) : value; label = p.reduceLabel ? p.reduceLabel(label, value) : String(value); } else { value = p.attrAccessor ? p.attrAccessor(p.valueAccessor(nodes)) : p.valueAccessor(nodes); label = value; } } else { value = itemData; label = itemData; } } if (pCfg.fields) { var v = fn ? fn(value) : value; coll.push(v); collStr.push(str && label != null ? str(label) : label != null ? label : String(v)); } else { var _v = fn ? fn(value) : value; ret[propsArr[i]] = { value: _v, label: str ? str(label) : label != null ? label : String(_v) }; if (p.field) { ret[propsArr[i]].source = { field: p.field.key(), key: sourceKey }; } } }; for (var j = 0; j < arr.length; j++) { _loop(j); } if (coll) { ret[propsArr[i]] = { value: typeof pCfg.value === 'function' ? pCfg.value(coll, item) : coll, label: typeof pCfg.label === 'function' ? pCfg.label(collStr, item) : collStr }; } } } var getHierarchy = function getHierarchy(cube, cache, config) { var rootPath = cube.qMode === 'K' ? '/qStackedDataPages/*/qData' : '/qTreeDataPages/*'; var childNodes = cube.qMode === 'K' ? 'qSubNodes' : 'qNodes'; var root = resolve(rootPath, cube); if (!root || !root[0]) { return null; } cache.tree = hierarchy(root[0], config.children || function (node) { return node[childNodes]; }); return cache.tree; }; function getHierarchyForSMode(dataset) { var matrix = dataset.raw().qDataPages.length ? dataset.raw().qDataPages[0].qMatrix : []; var order = getColumnOrder(dataset); var fields = dataset.fields(); var dimensions = dataset.fields().filter(function (f) { return f.type() === 'dimension'; }).map(function (f) { return order.indexOf(fields.indexOf(f)); }); var measures = dataset.fields().filter(function (f) { return f.type() === 'measure'; }).map(function (f) { return order.indexOf(fields.indexOf(f)); }); var root = { __id: '__root', qValues: [] }; var keys = { __root: root }; for (var r = 0; r < matrix.length; r++) { var row = matrix[r]; var id = '__root'; // let parent = root; var isNew = false; for (var c = 0; c < dimensions.length; c++) { var cell = row[dimensions[c]]; var key = "".concat(id, "__").concat(cell.qText); if (!keys[key]) { keys[key] = _objectSpread2({ __id: key, __parent: id, qValues: [] }, cell); isNew = true; } id = key; } if (isNew) { for (var _c = 0; _c < measures.length; _c++) { var _cell = row[measures[_c]]; keys[id].qValues.push(_cell); } } } var nodes = Object.keys(keys).map(function (key) { return keys[key]; }); var h = stratify().id(function (d) { return d.__id; }).parentId(function (d) { return d.__parent; })(nodes); return h; } var attachPropsAccessors = function attachPropsAccessors(_ref4) { var propsArr = _ref4.propsArr, props = _ref4.props, cube = _ref4.cube, cache = _ref4.cache, itemDepthObject = _ref4.itemDepthObject, f = _ref4.f; for (var i = 0; i < propsArr.length; i++) { var pCfg = props[propsArr[i]]; var arr = pCfg.fields ? pCfg.fields : [pCfg]; for (var j = 0; j < arr.length; j++) { var p = arr[j]; if (p.field !== f) { var depthObject = getFieldDepth(p.field, { cube: cube, cache: cache }); var accessors = getFieldAccessor$1(itemDepthObject, depthObject); p.accessor = accessors.nodeFn; // nodes accessor p.valueAccessor = accessors.valueFn; // cell accessor p.attrAccessor = accessors.attrFn; // attr cell accessor } } } }; function augment() { var config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var dataset = arguments.length > 1 ? arguments[1] : undefined; var cache = arguments.length > 2 ? arguments[2] : undefined; var util = arguments.length > 3 ? arguments[3] : undefined; var cube = dataset.raw(); var sourceKey = dataset.key(); var h = cube.qMode === 'S' ? getHierarchyForSMode(dataset) : getHierarchy(cube, cache, config); if (!h) { return null; } var height = h.height; var propDefs = []; for (var i = 0; i <= height; i++) { var f = null; if (i > 0) { if (cube.qMode === 'S') { var order = getDimensionColumnOrder(cube); var idx = order[i - 1]; f = cache.fields[idx]; } else { var _idx = cube.qEffectiveInterColumnSortOrder[i - 1]; // if (idx === -1) { // pseudo // let childIdx = node.parent.children.indexOf(node); // idx = cube.qDimensionInfo.length + childIdx; // measure field // } if (i > cube.qEffectiveInterColumnSortOrder.length) { _idx = cube.qDimensionInfo.length; } f = cache.fields[_idx]; } } var _util$normalizeConfig = util.normalizeConfig(_objectSpread2({}, config, { field: f ? f.key() : undefined }), dataset), props = _util$normalizeConfig.props, main = _util$normalizeConfig.main; var propsArr = Object.keys(props); propDefs[i] = { propsArr: propsArr, props: props, main: main }; var itemDepthObject = f ? getFieldDepth(f, { cube: cube, cache: cache }) : { fieldDepth: 0 }; attachPropsAccessors({ propsArr: propsArr, props: props, cube: cube, cache: cache, itemDepthObject: itemDepthObject, f: f }); } var replica = h.copy(); var replicaDescendants = replica.descendants(); var descendants = h.descendants(); for (var _i = 0; _i < descendants.length; _i++) { var _propsArr = propDefs[descendants[_i].depth].propsArr; var props = propDefs[descendants[_i].depth].props; var main = propDefs[descendants[_i].depth].main; var item = replicaDescendants[_i]; var itemData = item.data; // main.valueAccessor(currentOriginal); var ret = datumExtract$1(main, itemData, { key: sourceKey }); doIt({ propsArr: _propsArr, props: props, item: item, itemData: itemData, ret: ret, sourceKey: sourceKey, isTree: true }); descendants[_i].data = ret; } return h; } function extract$1(config, dataset, cache, util) { var cfgs = Array.isArray(config) ? config : [config]; var dataItems = []; for (var g = 0; g < cfgs.length; g++) { if (typeof cfgs[g].field !== 'undefined') { var cube = dataset.raw(); var sourceKey = dataset.key(); var h = getHierarchy(cube, cache, config); if (!h) { continue; } var f = _typeof(cfgs[g].field) === 'object' ? cfgs[g].field : dataset.field(cfgs[g].field); var _util$normalizeConfig2 = util.normalizeConfig(cfgs[g], dataset), props = _util$normalizeConfig2.props, main = _util$normalizeConfig2.main; var propsArr = Object.keys(props); var itemDepthObject = getFieldDepth(f, { cube: cube, cache: cache }); var _getFieldAccessor = getFieldAccessor$1({ fieldDepth: 0 }, itemDepthObject), nodeFn = _getFieldAccessor.nodeFn, attrFn = _getFieldAccessor.attrFn, valueFn = _getFieldAccessor.valueFn; attachPropsAccessors({ propsArr: propsArr, props: props, cube: cube, cache: cache, itemDepthObject: itemDepthObject, f: f }); var track = !!cfgs[g].trackBy; var trackType = _typeof(cfgs[g].trackBy); var tracker = {}; var trackedItems = []; var items = nodeFn(cache.tree); var mapped = []; for (var i = 0; i < items.length; i++) { var item = items[i]; var itemData = attrFn ? attrFn(valueFn(item)) : valueFn(item); var exclude = main.filter && !main.filter(itemData); if (exclude) { continue; } var ret = datumExtract$1(main, itemData, { key: sourceKey }); doIt({ propsArr: propsArr, props: props, item: item, itemData: itemData, ret: ret, sourceKey: sourceKey }); // collect items based on the trackBy value // items with the same trackBy value are placed in an array and reduced later if (track) { util.track({ cfg: cfgs[g], itemData: itemData, obj: ret, target: trackedItems, tracker: tracker, trackType: trackType }); } mapped.push(ret); } // reduce if items have been grouped if (track) { dataItems.push.apply(dataItems, _toConsumableArray(util.collect(trackedItems, { main: main, propsArr: propsArr, props: props }))); } else { dataItems.push.apply(dataItems, mapped); } } } return dataItems; } var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function createCommonjsModule(fn, module) { return module = { exports: {} }, fn(module, module.exports), module.exports; } var format_min = createCommonjsModule(function (module) { /*! javascript-number-formatter - v1.1.11 - http://mottie.github.com/javascript-number-formatter/ * © ecava */ !function(a,b){module.exports=b();}(commonjsGlobal,function(){return function(a,b){if(!a||isNaN(+b))return b;var c,d,e,f,g,h,i,j,k,l,m=a.length,n=a.search(/[0-9\-\+#]/),o=n>0?a.substring(0,n):"",p=a.split("").reverse().join(""),q=p.search(/[0-9\-\+#]/),r=m-q,s=a.substring(r,r+1),t=r+("."===s||","===s?1:0),u=q>0?a.substring(t,m):"";if(a=a.substring(n,t),b="-"===a.charAt(0)?-b:+b,c=b<0?b=-b:0,d=a.match(/[^\d\-\+#]/g),e=d&&d[d.length-1]||".",f=d&&d[1]&&d[0]||",",a=a.split(e),b=b.toFixed(a[1]&&a[1].length),b=+b+"",h=a[1]&&a[1].lastIndexOf("0"),j=b.split("."),(!j[1]||j[1]&&j[1].length<=h)&&(b=(+b).toFixed(h+1)),k=a[0].split(f),a[0]=k.join(""),g=a[0]&&a[0].indexOf("0"),g>-1)for(;j[0].length 10) { // limit to 10 decimal places value = value.slice(0, value.indexOf('.') + 11); } return value.replace('.', decimal || '.'); } // value must be an integer // value must not be in scientific notation function formatRoman(value, pattern) { var i, s = '', v = Number(String(value).slice(-3)), nThousands = (value - v) / 1000, decimal = [0, 1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900].reverse(), numeral = ['0', 'I', 'IV', 'V', 'IX', 'X', 'XL', 'L', 'XC', 'C', 'CD', 'D', 'CM'].reverse(); while (v > 0) { for (i = 0; i < decimal.length; i++) { if (decimal[i] <= v) { s += numeral[i]; v -= decimal[i]; break; } } } for (i = 0; i < nThousands; i++) { s = "M".concat(s); } if (pattern[1] !== pattern[1].toUpperCase()) { s = s.toLowerCase(); } return s; } function formatFunctional(value, pattern, d) { var temp; if (radix.test(pattern)) { value = formatRadix(value, Number(/\d{2}/.exec(pattern)[0]), pattern, d); } else if (oct.test(pattern)) { value = formatRadix(value, 8, pattern, d); } else if (dec.test(pattern)) { value = formatRadix(value, 10, pattern, d); } else if (hex.test(pattern)) { value = formatRadix(value, 16, pattern, d); } else if (bin.test(pattern)) { value = formatRadix(value, 2, pattern, d); } else if (rom.test(pattern)) { temp = ''; if (value < 0) { temp = '-'; value = -value; } value = Math.floor(value); if (value === 0) { value = '0'; } else if (value <= 500000) { // limit in engine value = formatRoman(value, pattern); value = temp + value; } else { value = pattern + temp + value.toExponential(0); // to return same result as engine } } return value; } function escape(value, flags, justStr) { var str = escapeRegExp(value); if (justStr) { return str; } return new RegExp(str || '', flags); } function createRegExp(thousand, decimal) { if (decimal) { decimal = escapeRegExp(decimal); } if (thousand) { thousand = escapeRegExp(thousand); } return new RegExp("(?:[#0]+".concat(thousand, ")?[#0]+(?:").concat(decimal, "[#0]+)?")); } function getAbbreviations(localeInfo, listSeparator) { if (!localeInfo || !localeInfo.qNumericalAbbreviation) { return SIprefixes; } var abbreviations = {}; var abbrs = localeInfo.qNumericalAbbreviation.split(listSeparator); abbrs.forEach(function (abbreviation) { var abbreviationTuple = abbreviation.split(':'); if (abbreviationTuple.length === 2) { abbreviations[abbreviationTuple[0]] = abbreviationTuple[1]; } }); return abbreviations; } function preparePattern(o, t, d) { var parts, lastPart, pattern = o.pattern, numericPattern, prefix, postfix, groupTemp, decTemp, temp, regex; if (pattern.indexOf('A') >= 0) { // abbreviate SI pattern = pattern.replace('A', ''); o.abbreviate = true; } // extract the numeric part from the pattern regex = createRegExp(t, d); numericPattern = pattern.match(regex); numericPattern = numericPattern ? numericPattern[0] : ''; prefix = numericPattern ? pattern.substr(0, pattern.indexOf(numericPattern)) : pattern; postfix = numericPattern ? pattern.substring(pattern.indexOf(numericPattern) + numericPattern.length) : ''; if (!numericPattern) { numericPattern = pattern ? '#' : '##########'; } if (t && t === d) { // ignore grouping if grouping separator is same as decimal separator // extract decimal part parts = numericPattern.split(d); lastPart = parts.pop(); numericPattern = parts.join('') + d + lastPart; t = ''; } // formatting library does not support multiple characters as separator (nor +-). // do a temporary replacement groupTemp = t; t = /,/.test(d) ? '¤' : ','; if (groupTemp) { numericPattern = numericPattern.replace(escape(groupTemp, 'g'), t); } decTemp = d; d = '.'; if (decTemp) { numericPattern = numericPattern.replace(escape(decTemp, 'g'), d); } temp = numericPattern.match(/#/g); temp = temp ? temp.length : 0; var splitPattern = pattern.split(decTemp); var matchPrecisionResult; if (splitPattern[1]) { matchPrecisionResult = splitPattern[1].match(prec); } o.prefix = prefix || ''; o.postfix = postfix || ''; o.pattern = pattern; o.maxPrecision = matchPrecisionResult ? matchPrecisionResult.length : 2; o.percentage = percentage.test(pattern); o.numericPattern = numericPattern || ''; o.numericRegex = new RegExp("".concat(escape(t, null, true), "|").concat(escape(d, null, true)), 'g'); o.groupTemp = groupTemp; o.decTemp = decTemp; o.t = t; o.d = d; o.temp = temp; } var NumberFormatter = /*#__PURE__*/ function () { /** * @name NumberFormatter * @constructs * @param {Object} localeInfo * @param {String} pattern * @param {String} [thousand] * @param {String} [decimal] * @param {String} [type] */ function NumberFormatter(localeInfo, pattern, thousand, decimal, type) { _classCallCheck(this, NumberFormatter); this.localeInfo = localeInfo; this.pattern = pattern; this.thousandDelimiter = thousand || ','; this.decimalDelimiter = decimal || '.'; this.type = type || 'numeric'; // FIXME qListSep? // this.patternSeparator = this.localeInfo && this.localeInfo.qListSep ? this.localeInfo.qListSep : ';'; this.patternSeparator = ';'; this.abbreviations = getAbbreviations(localeInfo, this.patternSeparator); this.prepare(); } _createClass(NumberFormatter, [{ key: "clone", value: function clone() { var n = new NumberFormatter(this.localeInfo, this.pattern, this.thousandDelimiter, this.decimalDelimiter, this.type); n.subtype = this.subtype; return n; } /** * Formats a number according to a specific pattern. * Use # for optional numbers and 0 for padding. * @param {Number} value Number to format. * @param {String} [pattern] The pattern to apply. * @param {String} [t] Grouping separator. * @param {String} [d] Decimal delimiter. * @example * format(10, "0") // 10; * format(10, "#") // 10; * format(10, "##.#") // 10; * format(10, "##.0") // 10.0; * format(10, "000") // 010; * format(10.123, "0.0") // 10.1; * format(10.123, "0.00##") // 10.123; // at least 2 decimals, never more than 4 * format(123456789, "#,###") // 123,456,789; * format(123456789, "####-####", "-") // 1-2345-6789; * format(10000, "#A") // 10k, A -> SI abbreviation * format(1234567, "#.###A") // 1.235M; * format(0.0001, "#.#A") // 0.1m; * * format(0.257, "0.0%") // 25.7%; // will multiply by 100 * format(9876, "$#,###") // $9,876; * format(-9876, "$#,###;$(#,###)") // $(9,876); // use ; for alternative formatting for negative values * format(10, "(r16)") // a; // radix 16 * format(15, "(hex)") // f; // same as (r16) * format(15, "(HEX)") // F; * format(10, "(bin)") // 1010; // same as (r02) * format(10, "(oct)") // 12; // same as (r08) */ }, { key: "format", value: function format(value, pattern, t, d) { this.prepare(pattern, t, d); return this.formatValue(value); } }, { key: "prepare", value: function prepare(pattern, t, d) { var prep; if (typeof pattern === 'undefined') { pattern = this.pattern; } if (typeof t === 'undefined') { t = this.thousandDelimiter; } if (typeof d === 'undefined') { d = this.decimalDelimiter; } if (!pattern) { this._prepared = { pattern: false }; return; } this._prepared = { positive: { d: d, t: t, abbreviate: false, isFunctional: false, prefix: '', postfix: '' }, negative: { d: d, t: t, abbreviate: false, isFunctional: false, prefix: '', postfix: '' }, zero: { d: d, t: t, abbreviate: false, isFunctional: false, prefix: '', postfix: '' } }; prep = this._prepared; pattern = pattern.split(this.patternSeparator); prep.positive.pattern = pattern[0]; prep.negative.pattern = pattern[1]; prep.zero.pattern = pattern[2]; if (functional.test(pattern[0])) { prep.positive.isFunctional = true; } if (!pattern[1]) { prep.negative = false; } else if (functional.test(pattern[1])) { prep.negative.isFunctional = true; } if (!pattern[2]) { prep.zero = false; } else if (functional.test(pattern[2])) { prep.zero.isFunctional = true; } if (!prep.positive.isFunctional) { preparePattern(prep.positive, t, d); } if (prep.negative && !prep.negative.isFunctional) { preparePattern(prep.negative, t, d); } if (prep.zero && !prep.zero.isFunctional) { preparePattern(prep.zero, t, d); } } }, { key: "formatValue", value: function formatValue(value) { var prep = this._prepared, temp, exponent, abbr = '', absValue, num, sciValue = '', d, t, i, numericPattern, decimalPartPattern, original = value; if (isNaN(value)) { return "".concat(original); } value = +value; if (prep.pattern === false) { return value.toString(); } if (value === 0 && prep.zero) { prep = prep.zero; return prep.pattern; } if (value < 0 && prep.negative) { prep = prep.negative; value = -value; } else { prep = prep.positive; } d = prep.d; t = prep.t; if (prep.isFunctional) { value = formatFunctional(value, prep.pattern, d); } else { if (prep.percentage) { value *= 100; } if (prep.abbreviate) { var abbrArray = Object.keys(this.abbreviations).map(function (key) { return parseInt(key, 10); }).sort(function (a, b) { return a - b; }); var lowerAbbreviation; var upperAbbreviation = abbrArray[0]; i = 0; exponent = Number(Number(value).toExponential().split('e')[1]); while (upperAbbreviation <= exponent && i < abbrArray.length) { i++; upperAbbreviation = abbrArray[i]; } if (i > 0) { lowerAbbreviation = abbrArray[i - 1]; } var suggestedAbbrExponent; // value and lower abbreviation is for values above 10, use the lower (move to the left <==) if (lowerAbbreviation && exponent > 0 && lowerAbbreviation > 0) { suggestedAbbrExponent = lowerAbbreviation; // value and lower abbreviation is for values below 0.1 (move to the right ==>) } else if (exponent < 0 && lowerAbbreviation < 0 || !lowerAbbreviation) { // upper abbreviation is also for values below 0.1 and precision allows for using the upper abbreviation(move to the right ==>) if (upperAbbreviation < 0 && upperAbbreviation - exponent <= prep.maxPrecision) { suggestedAbbrExponent = upperAbbreviation; // lower abbrevaition is smaller than exponent and we can't get away with not abbreviating } else if (lowerAbbreviation <= exponent && !(upperAbbreviation > 0 && -exponent <= prep.maxPrecision)) { // (move to left <==) suggestedAbbrExponent = lowerAbbreviation; } } if (suggestedAbbrExponent) { abbr = this.abbreviations[suggestedAbbrExponent]; value /= Math.pow(10, suggestedAbbrExponent); } } absValue = Math.abs(value); temp = prep.temp; numericPattern = prep.numericPattern; decimalPartPattern = numericPattern.split(d)[1]; if (this.type === 'I') { value = Math.round(value); } num = value; if (!decimalPartPattern && numericPattern.slice(-1)[0] === '#') { if (absValue >= Math.pow(10, temp) || absValue < 1 || absValue < 1e-4) { if (value === 0) { value = '0'; } else if (absValue < 1e-4 || absValue >= 1e20) { // engine always formats values < 1e-4 in scientific form, values >= 1e20 can only be represented in scientific form value = num.toExponential(Math.max(1, Math.min(14, temp)) - 1); value = value.replace(/\.?0+(?=e)/, ''); sciValue = ''; } else { value = value.toPrecision(Math.max(1, Math.min(14, temp))); if (value.indexOf('.') >= 0) { value = value.replace(value.indexOf('e') < 0 ? /0+$/ : /\.?0+(?=e)/, ''); value = value.replace('.', d); } } } else { numericPattern += d; temp = Math.max(0, Math.min(20, temp - Math.ceil(Math.log(absValue) / Math.log(10)))); for (i = 0; i < temp; i++) { numericPattern += '#'; } value = format_min(numericPattern, value); } } else if (absValue >= 1e15 || absValue > 0 && absValue <= 1e-14) { value = absValue ? absValue.toExponential(15).replace(/\.?0+(?=e)/, '') : '0'; } else { var wholePart = Number(value.toFixed(Math.min(20, decimalPartPattern ? decimalPartPattern.length : 0)).split('.')[0]); var wholePartPattern = numericPattern.split(d)[0]; wholePartPattern += d; value = format_min(wholePartPattern, wholePart) || '0'; if (decimalPartPattern) { var nDecimals = Math.max(0, Math.min(14, decimalPartPattern.length)); // the length of e.g. 0000##### var nZeroes = decimalPartPattern.replace(/#+$/, '').length; var decimalPart = (this.type === 'I' ? 0 : absValue % 1).toFixed(nDecimals).slice(2).replace(/0+$/, ''); // remove trailing zeroes for (i = decimalPart.length; i < nZeroes; i++) { decimalPart += '0'; } if (decimalPart) { value += d + decimalPart; } } else if (wholePart === 0) { // to avoid "-" being prefixed to value num = 0; } } value = value.replace(prep.numericRegex, function (m) { if (m === t) { return prep.groupTemp; } if (m === d) { return prep.decTemp; } return ''; }); if (num < 0 && !/^-/.test(value)) { value = "-".concat(value); } } return prep.prefix + value + sciValue + abbr + prep.postfix; } }], [{ key: "getStaticFormatter", value: function getStaticFormatter() { return { prepare: function prepare() {}, formatValue: function formatValue(v) { return "".concat(v); } }; } }]); return NumberFormatter; }(); function numberFormatFactory() { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _construct(NumberFormatter, args); } function memoize(func) { var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var _opts$size = opts.size, size = _opts$size === void 0 ? 5000 : _opts$size, _opts$multipleArgumen = opts.multipleArguments, multipleArguments = _opts$multipleArgumen === void 0 ? false : _opts$multipleArgumen, _opts$toKey = opts.toKey, toKey = _opts$toKey === void 0 ? function (arg) { return arg; } : _opts$toKey; var cache = Object.create(null); var index = Object.create(null); var counter = 0; var fifo = 0; // First-In-First-Out index var _cacher2; var k; if (multipleArguments) { _cacher2 = function cacher() { k = toKey.apply(void 0, arguments); if (_cacher2.has(k)) { return _cacher2.get(k); } return _cacher2.set(k, func.apply(void 0, arguments)); }; } else { _cacher2 = function _cacher(arg) { k = toKey(arg); if (_cacher2.has(k)) { return _cacher2.get(k); } return _cacher2.set(k, func(arg)); }; } _cacher2.set = function (key, val) { if (counter >= size) { delete cache[index[fifo]]; delete index[fifo]; counter--; fifo++; } cache[key] = val; index[counter] = key; counter++; return val; }; _cacher2.get = function (key) { return cache[key]; }; _cacher2.has = function (key) { return key in cache; }; _cacher2.clear = function () { cache = Object.create(null); index = Object.create(null); counter = 0; fifo = 0; }; _cacher2.size = function () { return counter; }; return _cacher2; } function formatter(pattern, thousand, decimal, qType, localeInfo) { var qformat = numberFormatFactory(localeInfo, pattern, thousand, decimal, qType); var memoized = memoize(qformat.formatValue.bind(qformat), { // Handle NaN and cases where toString yields different result than +operator. Ex. a Date. toKey: function toKey(value) { return isNaN(value) ? value : +value; } }); /** * Format a value according to the specified pattern created at construct * * @param {Number} value The number to be formatted * @return {String} [description] */ function format(value) { return memoized(value); } /** * Format a value according to a specific pattern * that is not the one specified in the constructor * * @param {String} p Pattern * @param {Number} v Value * @param {String} t Thousand * @param {String} d Decimal * @return {String} Formatted value */ format.format = function formatFn(p, v, t, d) { memoized.clear(); return qformat.format(v, p, t, d); }; /** * Change the pattern on existing formatter * * @param {String} p Pattern (optional) * @return {String} Returns the pattern */ format.pattern = function patternFn(p) { if (p) { memoized.clear(); qformat.pattern = p; qformat.prepare(); } return qformat.pattern; }; /** * Set the locale for the formatter * * @param {Object} args Locale object for formatting * @return {Undefined} Returns nothing */ /* format.locale = function( ...args ) { locale = formatLocale( ...args ); d3format = locale.format( pattern ); return this; }; */ return format; } /* eslint import/prefer-default-export: 0 */ var TYPES = { AUTO: 'U', INTEGER: 'I', NUMBER: 'R', FIXED_TO: 'F', MONEY: 'M', DATE: 'D', TIME: 'T', DATE_TIME: 'TS', INTERVAL: 'IV' }; var DAYS = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']; var DAYS_ABBR = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']; var MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; var MONTHS_ABBR = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; var SECONDS_PER_DAY = 86400; function pad(s, n) { for (var i = s.length; i < n; i++) { s = "0".concat(s); } return s; } function parseDate(d, twelveFormat) { var h = d.getUTCHours(); var day = d.getUTCDay() - 1; if (twelveFormat) { h %= 12; if (!h) { // h == 0 -> 12 h = 12; } } if (day < 0) { day = 6; } return { year: d.getUTCFullYear(), month: d.getUTCMonth(), day: day, date: d.getUTCDate(), h: h, m: d.getUTCMinutes(), s: d.getUTCSeconds(), f: d.getUTCMilliseconds(), t: d.getUTCHours() >= 12 ? 'pm' : 'am' }; } function getRemainder(value) { var s = value.toString().split('.'); if (s[1]) { s = Number("0.".concat(s[1])); } else { return 0; } return s; } function parseIntervalDays(days) { var d = days; var h = 24 * getRemainder(d); var m = 60 * getRemainder(h); var s = 60 * getRemainder(m); var ms = 1000 * getRemainder(s); return { d: Math.floor(d), h: Math.floor(h), m: Math.floor(m), s: Math.floor(s), f: Math.round(ms) }; } function parseInterval(days, pattern) { var units = parseIntervalDays(days), d = units.d, h = units.h, m = units.m, s = units.s, f = units.f, w = 0, date; if (/w+|t+/gi.test(pattern)) { date = new Date(Date.UTC(1899, 11, 30 + Math.floor(days), 0, 0, Math.round(SECONDS_PER_DAY * (days - Math.floor(days))))); if (isNaN(date.getTime())) { date = null; } } if (!/D+/gi.test(pattern)) { h += d * 24; } if (!/h+/gi.test(pattern)) { m += h * 60; } if (!/m+/gi.test(pattern)) { s += m * 60; } if (/w+/gi.test(pattern)) { w = date ? date.getDay() - 1 : 0; if (w < 0) { w = 6; } } var someT = ''; if (date) { someT = date.getUTCHours() >= 12 ? 'pm' : 'am'; } return { year: 0, month: 0, day: w, date: d, h: h, m: m, s: s, f: f, t: someT }; } function getMasks(inst, d) { return { 'Y+|y+': { Y: "".concat(Number("".concat(d.year).slice(-2))), YY: pad("".concat(d.year).slice(-2), 2), YYY: pad("".concat(d.year).slice(-3), 3), def: function def(m) { // default return pad("".concat(d.year), m.length); } }, 'M+': { M: d.month + 1, MM: pad("".concat(d.month + 1), 2), MMM: inst.locale_months_abbr[d.month], def: inst.locale_months[d.month] }, 'W+|w+': { W: d.day, WW: pad("".concat(d.day), 2), WWW: inst.locale_days_abbr[d.day], def: inst.locale_days[d.day] }, 'D+|d+': { D: d.date, def: function def(m) { return pad("".concat(d.date), m.length); } }, 'h+|H+': { h: d.h, def: function def(m) { return pad("".concat(d.h), m.length); } }, 'm+': { m: d.m, def: function def(m) { return pad("".concat(d.m), m.length); } }, 's+|S+': { s: d.s, def: function def(m) { return pad("".concat(d.s), m.length); } }, 'f+|F+': { def: function def(m) { var f = "".concat(d.f), n = m.length - f.length; if (n > 0) { for (var i = 0; i < n; i++) { f += '0'; } } else if (n < 0) { f = f.slice(0, m.length); } return f; } }, 't{1,2}|T{1,2}': { def: function def(m) { var t = d.t; if (m[0].toUpperCase() === m[0]) { t = t.toUpperCase(); } t = t.slice(0, m.length); return t; } } }; } var DateFormatter = /*#__PURE__*/ function () { /** * @name DateFormatter * @constructs * @param {Object} localeInfo * @param {String} pattern */ function DateFormatter(localeInfo, pattern, qtype) { _classCallCheck(this, DateFormatter); var info = localeInfo || {}; if (!info.qCalendarStrings) { info.qCalendarStrings = { qLongDayNames: DAYS, qDayNames: DAYS_ABBR, qLongMonthNames: MONTHS, qMonthNames: MONTHS_ABBR }; } this.localeInfo = info; this.locale_days = info.qCalendarStrings.qLongDayNames.slice(); this.locale_days_abbr = info.qCalendarStrings.qDayNames.slice(); this.locale_months = info.qCalendarStrings.qLongMonthNames.slice(); this.locale_months_abbr = info.qCalendarStrings.qMonthNames.slice(); if (!pattern) { var _patternMap; var patternMap = (_patternMap = {}, _defineProperty(_patternMap, TYPES.TIME, info.qTimeFmt || 'hh:mm:ss'), _defineProperty(_patternMap, TYPES.DATE, info.qDateFmt || 'YYYY-MM-DD'), _defineProperty(_patternMap, TYPES.DATE_TIME, info.qTimestampFmt || 'YYYY-MM-DD hh:mm:ss'), _patternMap); pattern = patternMap[qtype]; } this.pattern = pattern; } _createClass(DateFormatter, [{ key: "clone", value: function clone() { var n = new DateFormatter(this.localeInfo, this.pattern); n.subtype = this.subtype; return n; } /** * Formats a date according to given pattern * @param {Date} date The date to format. * @param {String} pattern The desired format of the date * var d = new Date(2013, 8, 15, 13, 55, 40, 987); * var n = new DateFormatter(); * @example * m.format( d, 'YYYY-MM-DD hh:mm:ss.ffff') // 2013-08-15 13:55:40.9870 * m.format( d, 'h:m:s tt') // 1:55:40 pm * m.format( d, 'h:m:s TT') // 1:55:40 PM * m.format( d, 'M/D/YYYY') // 8/15/2013 * m.format( d, 'WWWW DD MMM') // Thursday 15 Aug * m.format( d, 'WWW DD MMMM @ hh:mm:ss') // Thu 15 August @ 13:55:40 */ }, { key: "format", value: function format(date, pattern) { // Fallback pattern is set in constructor if (!pattern) { pattern = this.pattern ? this.pattern : 'YYYY-MM-DD hh:mm:ss'; } pattern = pattern.replace(/\[.+]|\[|]/g, ''); var hasTwelveFlag = /t+/ig.test(pattern); var parsedDate; if (date instanceof Date) { parsedDate = parseDate(date, hasTwelveFlag); } else { if (date < 0) { // parseInterval don't support for negative values date = -date; pattern = "-".concat(pattern); } parsedDate = parseInterval(date, pattern); } // remove [] and everything inside it var masks = getMasks(this, parsedDate); var masksArr = []; for (var mask in masks) { if (Object.prototype.hasOwnProperty.call(masks, mask)) { masksArr.push(mask); } } var dateTimeRegex = new RegExp(masksArr.join('|'), 'g'); var result = pattern.replace(dateTimeRegex, function (m) { var r; var mask; for (mask in masks) { if (Object.prototype.hasOwnProperty.call(masks, mask)) { r = new RegExp(mask); if (r.test(m)) { break; } } } if (!r) { return ''; } var value; for (var submask in masks[mask]) { if (submask === m || submask.toLowerCase() === m) { value = masks[mask][submask]; if (typeof value === 'undefined') { value = masks[mask][submask.toLowerCase()]; } break; } } if (typeof value === 'undefined') { value = masks[mask].def; } if (typeof value === 'function') { value = value(m); } return value; }); return result; } }]); return DateFormatter; }(); function dateFormatFactory() { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _construct(DateFormatter, args); } var MS_PER_DAY = 86400000; function QlikTimeToDate(value) { return new Date(Date.UTC(1899, 11, 30 + Math.floor(value), 0, 0, 0, Math.round(MS_PER_DAY * (value - Math.floor(value))))); } function formatter$1(pattern) { var qtype = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'TS'; var localeInfo = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; var qformat = dateFormatFactory(localeInfo, pattern, qtype); var memoized = memoize(qformat.format.bind(qformat), { toKey: function toKey(date) { return _typeof(date) === 'object' && typeof date.getTime === 'function' ? date.getTime() : date; } }); /** * Prepare a value according to the specified qtype * * @param {Number} value The value to be formatted * @return {Number} The converted value (if applied) */ function prepare(value) { if (qtype !== TYPES.INTERVAL) { return QlikTimeToDate(value); } return value; } /** * Format a value according to the specified pattern created at construct * * @param {Date} value The number to be formatted * @return {String} [description] */ function format(value) { value = prepare(value); return memoized(value); } /** * Format a value according to a specific pattern * that is not the one specified in the constructor * * @param {String} p Pattern * @param {Date} v Value * @return {String} Formatted value */ format.format = function formatFn(p, v) { memoized.clear(); v = prepare(v); return qformat.format(v, p); }; /** * Set the locale for the formatter * * @param {Object} args Locale object for formatting * @return {Undefined} Returns nothing */ format.locale = function locale(li) { qformat = dateFormatFactory(li, pattern, qtype); memoized = memoize(qformat.format.bind(qformat), { toKey: function toKey(date) { return _typeof(date) === 'object' ? date.getTime() : date; } }); return this; }; /** * Get or set the QType * * @param {String} nqt New qType (optional) * @return {String} Current qtype */ format.qtype = function qtypeFn(nqt) { if (nqt !== undefined) { qtype = nqt; memoized.clear(); } return qtype; }; return format; } function createFromMetaInfo(meta, localeInfo) { if (meta && meta.qNumFormat && ['D', 'T', 'TS', 'IV'].indexOf(meta.qNumFormat.qType) !== -1) { return formatter$1(meta.qNumFormat.qFmt, meta.qNumFormat.qType, localeInfo); } var pattern = '#'; var thousand = localeInfo && typeof localeInfo.qThousandSep !== 'undefined' ? localeInfo.qThousandSep : ','; var decimal = localeInfo && typeof localeInfo.qDecimalSep !== 'undefined' ? localeInfo.qDecimalSep : '.'; var type = 'U'; var isAuto = meta && !!meta.qIsAutoFormat; if (meta && meta.qNumFormat) { pattern = meta.qNumFormat.qFmt || pattern; thousand = meta.qNumFormat.qThou || thousand; decimal = meta.qNumFormat.qDec || decimal; type = meta.qNumFormat.qType || type; isAuto = isAuto && ['M'].indexOf(meta.qNumFormat.qType) === -1; } else { isAuto = true; } if (isAuto || type === 'U') { pattern = "#".concat(decimal, "##A"); type = 'U'; } return formatter(pattern, thousand, decimal, type, localeInfo); } function qField() { var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, meta = _ref.meta, _id = _ref.id, _key = _ref.key, localeInfo = _ref.localeInfo, fieldExtractor = _ref.fieldExtractor, value = _ref.value, _type = _ref.type, sourceField = _ref.sourceField; var values; var valueFn = value || (_type === 'dimension' ? function (d) { return d.qElemNo; } : function (d) { return d.qValue; }); var labelFn = function labelFn(d) { return d.qText || ''; }; var reduce = _type === 'dimension' ? 'first' : 'avg'; var _formatter = createFromMetaInfo(meta, localeInfo); var reduceLabel = _type === 'dimension' ? 'first' : function (labels, v) { return _formatter(v); }; var f = { id: function id() { return _id; }, key: function key() { return _key; }, raw: function raw() { return meta; }, title: function title() { return meta.qFallbackTitle || meta.label; }, type: function type() { return _type; }, origin: function origin() { return sourceField; }, items: function items() { if (!values) { values = fieldExtractor(f); } return values; }, min: function min() { return meta.qMin; }, max: function max() { return meta.qMax; }, value: valueFn, label: labelFn, reduce: reduce, reduceLabel: reduceLabel, formatter: function formatter() { return _formatter; }, tags: function tags() { return meta.qTags; } }; return f; } function createFields(path, obj, prefix, parentKey, opts) { return (obj[path] || []).map(function (meta, i) { var fieldKey = "".concat(parentKey ? "".concat(parentKey, "/") : '').concat(path, "/").concat(i); var f = { instance: qField(extend({ id: "".concat(prefix ? "".concat(prefix, "/") : '').concat(fieldKey), key: fieldKey, meta: meta }, opts)) }; f.attrDims = createFields('qAttrDimInfo', meta, prefix, fieldKey, extend({}, opts, { value: function value(v) { return v.qElemNo; }, type: 'dimension' })); f.attrExps = createFields('qAttrExprInfo', meta, prefix, fieldKey, extend({}, opts, { value: function value(v) { return v.qNum; }, type: 'measure' })); f.measures = createFields('qMeasureInfo', meta, prefix, fieldKey, extend({}, opts, { value: function value(v) { return v.qValue; }, type: 'measure' })); return f; }); } function q() { var _cache$wrappedFields, _cache$wrappedFields2, _cache$allFields; var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, _key = _ref.key, data = _ref.data, _ref$config = _ref.config, config = _ref$config === void 0 ? {} : _ref$config; var cache = { fields: [], wrappedFields: [], allFields: [], virtualFields: [] }; var cube = data; if (!cube) { throw new Error('Missing "data" input'); } if (!cube.qDimensionInfo) { throw new Error('The "data" input is not recognized as a hypercube'); } var deps = q.util; var opts = { cache: cache, cube: cube, localeInfo: config.localeInfo, fieldExtractor: null, pages: null, hierarchy: function hierarchy() { return null; }, virtualFields: config.virtualFields }; var dataset = { key: function key() { return _key; }, raw: function raw() { return cube; }, field: function field(query) { return findField(query, opts); }, fields: function fields() { return cache.fields.slice(); }, extract: function extract(extractionConfig) { return opts.extractor(extractionConfig, dataset, cache, deps); }, hierarchy: function hierarchy(hierarchyConfig) { return opts.hierarchy(hierarchyConfig, dataset, cache, deps); }, _cache: function _cache() { return cache; } }; if (cube.qMode === 'K' || cube.qMode === 'T' || !cube.qMode && cube.qNodesOnDim) { opts.extractor = extract$1; opts.hierarchy = augment; opts.pages = cube.qMode === 'K' ? cube.qStackedDataPages : cube.qTreeDataPages; } else if (cube.qMode === 'S') { opts.extractor = extract; opts.pages = cube.qDataPages; opts.hierarchy = augment; } else { opts.extractor = function () { return []; }; // TODO - throw unsupported error? } opts.fieldExtractor = function (f) { return opts.extractor({ field: f }, dataset, cache, deps); }; var dimAcc = cube.qMode === 'S' ? function (d) { return d.qElemNumber; } : undefined; var measAcc = cube.qMode === 'S' ? function (d) { return d.qNum; } : undefined; (_cache$wrappedFields = cache.wrappedFields).push.apply(_cache$wrappedFields, _toConsumableArray(createFields('qDimensionInfo', cube, _key, '', extend({}, opts, { value: dimAcc, type: 'dimension' })))); (_cache$wrappedFields2 = cache.wrappedFields).push.apply(_cache$wrappedFields2, _toConsumableArray(createFields('qMeasureInfo', cube, _key, '', extend({}, opts, { value: measAcc, type: 'measure' })))); cache.fields = cache.wrappedFields.map(function (f) { return f.instance; }); var traverse = function traverse(arr) { arr.forEach(function (f) { cache.allFields.push(f.instance); traverse(f.measures); traverse(f.attrDims); traverse(f.attrExps); }); }; traverse(cache.wrappedFields); (config.virtualFields || []).forEach(function (v) { // key: 'temporal', // from: 'qDimensionInfo/0', // override: { // value: v => v.qNum, // }, var sourceField = dataset.field(v.from); var f = qField(_objectSpread2({ meta: sourceField.raw(), id: "".concat(_key, "/").concat(v.key), sourceField: sourceField, fieldExtractor: function fieldExtractor(ff) { return opts.extractor({ field: ff }, dataset, cache, deps); }, key: v.key, type: sourceField.type(), localeInfo: opts.localeInfo, value: sourceField.value }, v.override || {})); cache.virtualFields.push(f); }); (_cache$allFields = cache.allFields).push.apply(_cache$allFields, _toConsumableArray(cache.virtualFields)); return dataset; } var LAYOUT_TO_PROP = [['qHyperCube', 'qHyperCubeDef'], ['qTreeData', 'qTreeDataDef'], ['qDimensionInfo', 'qDimensions'], ['qMeasureInfo', 'qMeasures'], ['qAttrDimInfo', 'qAttributeDimensions'], ['qAttrExprInfo', 'qAttributeExpressions']]; var DIM_RX$1 = /\/qDimensionInfo(?:\/(\d+))?/; var M_RX$1 = /\/qMeasureInfo\/(\d+)/; var ATTR_DIM_RX$1 = /\/qAttrDimInfo\/(\d+)(?:\/(\d+))?/; var ATTR_EXPR_RX$1 = /\/qAttrExprInfo\/(\d+)/; var HC_RX = /\/?qHyperCube/; var TD_RX = /\/?qTreeData/; var SHORTEN_HC = function SHORTEN_HC(path) { return "".concat(path.substr(0, path.indexOf('/qHyperCubeDef') + 14)); }; // 14 = length of '/qHyperCubeDef' var SHORTEN_TD = function SHORTEN_TD(path) { return "".concat(path.substr(0, path.indexOf('/qTreeDataDef') + 13)); }; // 13 = length of '/qTreeDataDef' function extractFieldFromId(id, layout) { var path = id; var dimensionIdx = -1; var measureIdx = -1; var pathToCube = ''; var shortenizer = function shortenizer(p) { return p; }; if (HC_RX.test(id)) { pathToCube = "".concat(path.substr(0, path.indexOf('qHyperCube') + 10)); // 10 = length of 'qHyperCube' shortenizer = SHORTEN_HC; } else if (TD_RX.test(id)) { pathToCube = "".concat(path.substr(0, path.indexOf('qTreeData') + 9)); // 9 = length of 'qTreeData' shortenizer = SHORTEN_TD; } var shortenPath = true; if (DIM_RX$1.test(id)) { dimensionIdx = +DIM_RX$1.exec(id)[1]; } if (M_RX$1.test(id)) { measureIdx = +M_RX$1.exec(id)[1]; } if (ATTR_DIM_RX$1.test(id)) { measureIdx = -1; dimensionIdx = 0; var attrCol = +ATTR_DIM_RX$1.exec(path)[2]; if (!isNaN(attrCol)) { dimensionIdx = attrCol; path = path.replace(/\/\d+$/, ''); } shortenPath = false; } if (ATTR_EXPR_RX$1.test(id)) { // depends on number of measures + number of attr expressions // in dimensions and measures before this one var offset = measureIdx; if (layout) { measureIdx = 0; var hc = resolve(pathToCube, layout); // offset by number of measures measureIdx += (hc.qMeasureInfo || []).length; // offset by total number of attr expr in dimensions // (assuming attr expr in dimensions are ordered first) if (dimensionIdx > -1) { measureIdx = hc.qDimensionInfo.slice(0, dimensionIdx).reduce(function (v, dim) { return v + dim.qAttrExprInfo.length; }, measureIdx); dimensionIdx = -1; } else { measureIdx = hc.qDimensionInfo.reduce(function (v, dim) { return v + dim.qAttrExprInfo.length; }, measureIdx); // offset by total number of attr expr in measures before 'index' measureIdx = hc.qMeasureInfo.slice(0, offset).reduce(function (v, meas) { return v + meas.qAttrExprInfo.length; }, measureIdx); } // offset by the actual column value for the attribute expression itself measureIdx += +ATTR_EXPR_RX$1.exec(path)[1]; } else if (dimensionIdx > -1) { dimensionIdx = -1; measureIdx = +ATTR_EXPR_RX$1.exec(path)[1]; } else { measureIdx += +ATTR_EXPR_RX$1.exec(path)[1] + 1; } } LAYOUT_TO_PROP.forEach(function (_ref) { var _ref2 = _slicedToArray(_ref, 2), v = _ref2[0], prop = _ref2[1]; path = path.replace(v, prop); }); if (shortenPath) { path = shortenizer(path); } if (path && path[0] !== '/') { path = "/".concat(path); } return { measureIdx: measureIdx, dimensionIdx: dimensionIdx, path: path }; } /** * Helper method to generate suitable QIX selection methods and parameters based on a brush instance. * @alias brush * @memberof picasso.q * @param {brush} brush A brush instance * @param {object} [opts] * @param {boolean} [opts.byCells=false] Whether to prefer selection by row index. * @param {string} [opts.primarySource] Field source to extract row indices from. If not specified, indices from first source are used. * @param {object} [layout] QIX data layout. Needed only when brushing on attribute expressions, to be able to calculate the measure index. * @return {object[]} An array of relevant selections */ function qBrush(brush) { var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var layout = arguments.length > 2 ? arguments[2] : undefined; var byCells = opts.byCells; var primarySource = opts.primarySource; var selections = []; var methods = {}; var isActive = brush.isActive(); var hasValues = false; brush.brushes().forEach(function (b) { var info = extractFieldFromId(b.id, layout); if (b.type === 'range' && info.measureIdx > -1 && info.dimensionIdx > -1) { var ranges = b.brush.ranges(); if (ranges.length) { hasValues = true; if (!methods.multiRangeSelectTreeDataValues) { methods.multiRangeSelectTreeDataValues = { path: info.path, ranges: [] }; } ranges.forEach(function (range) { return methods.multiRangeSelectTreeDataValues.ranges.push({ qMeasureIx: info.measureIdx, qDimensionIx: info.dimensionIdx, qRange: { qMin: range.min, qMax: range.max, qMinInclEq: true, qMaxInclEq: true } }); }); } } else { if (b.type === 'range' && info.measureIdx > -1) { var _ranges = b.brush.ranges(); if (_ranges.length) { hasValues = true; if (!methods.rangeSelectHyperCubeValues) { methods.rangeSelectHyperCubeValues = { path: info.path, ranges: [] }; } _ranges.forEach(function (range) { return methods.rangeSelectHyperCubeValues.ranges.push({ qMeasureIx: info.measureIdx, qRange: { qMin: range.min, qMax: range.max, qMinInclEq: true, qMaxInclEq: true } }); }); } } if (b.type === 'range' && info.dimensionIdx > -1) { var _ranges2 = b.brush.ranges(); if (_ranges2.length) { hasValues = true; if (!methods.selectHyperCubeContinuousRange) { methods.selectHyperCubeContinuousRange = { path: info.path, ranges: [] }; } _ranges2.forEach(function (range) { return methods.selectHyperCubeContinuousRange.ranges.push({ qDimIx: info.dimensionIdx, qRange: { qMin: range.min, qMax: range.max, qMinInclEq: true, qMaxInclEq: false } }); }); } } if (b.type === 'value' && info.dimensionIdx > -1) { if (byCells) { if (layout && layout.qHyperCube && (layout.qHyperCube.qMode === 'P' || layout.qHyperCube.qMode === 'T' || layout.qHyperCube.qMode === 'K')) { var hyperCube = layout.qHyperCube; var noOfLeftDims = hyperCube.qNoOfLeftDims; var dimInterColSortIdx = hyperCube.qEffectiveInterColumnSortOrder.indexOf(info.dimensionIdx); if (!methods.selectPivotCells) { methods.selectPivotCells = { path: info.path, cells: [] }; } if (b.id === primarySource || !primarySource && methods.selectPivotCells.cells.length === 0) { var validValues = b.brush.values().map(function (s) { return +s; }).filter(function (v) { return !isNaN(v); }); if ((noOfLeftDims === 0 || dimInterColSortIdx >= noOfLeftDims) && noOfLeftDims > -1) { validValues.forEach(function (val) { methods.selectPivotCells.cells.push({ qType: 'T', qCol: val, qRow: dimInterColSortIdx - noOfLeftDims }); }); } else { validValues.forEach(function (val) { methods.selectPivotCells.cells.push({ qType: 'L', qCol: info.dimensionIdx, qRow: val }); }); } hasValues = !!methods.selectPivotCells.cells.length; } } else { if (!methods.selectHyperCubeCells) { methods.selectHyperCubeCells = { path: info.path, cols: [] }; } methods.selectHyperCubeCells.cols.push(info.dimensionIdx); if (b.id === primarySource || !primarySource && !methods.selectHyperCubeCells.values) { methods.selectHyperCubeCells.values = b.brush.values().map(function (s) { return +s; }).filter(function (v) { return !isNaN(v); }); hasValues = !!methods.selectHyperCubeCells.values.length; } } } else { var values = b.brush.values().map(function (s) { return +s; }).filter(function (v) { return !isNaN(v); }); hasValues = !!values.length; selections.push({ params: [info.path, info.dimensionIdx, values, false], method: 'selectHyperCubeValues' }); } } } }); if (!hasValues && isActive) { return [{ method: 'resetMadeSelections', params: [] }]; } if (methods.rangeSelectHyperCubeValues) { selections.push({ method: 'rangeSelectHyperCubeValues', params: [methods.rangeSelectHyperCubeValues.path, methods.rangeSelectHyperCubeValues.ranges, [], true] }); } if (methods.selectHyperCubeContinuousRange) { selections.push({ method: 'selectHyperCubeContinuousRange', params: [methods.selectHyperCubeContinuousRange.path, methods.selectHyperCubeContinuousRange.ranges] }); } if (methods.selectHyperCubeCells) { selections.push({ method: 'selectHyperCubeCells', params: [methods.selectHyperCubeCells.path, methods.selectHyperCubeCells.values, methods.selectHyperCubeCells.cols] }); } if (methods.selectPivotCells) { selections.push({ method: 'selectPivotCells', params: [methods.selectPivotCells.path, methods.selectPivotCells.cells] }); } if (methods.multiRangeSelectTreeDataValues) { selections.push({ method: 'multiRangeSelectTreeDataValues', params: [methods.multiRangeSelectTreeDataValues.path, methods.multiRangeSelectTreeDataValues.ranges] }); } return selections; } function initialize(picasso) { q.util = picasso.data('matrix').util; picasso.data('q', q); picasso.formatter('q-number', formatter); picasso.formatter('q-time', formatter$1); } initialize.qBrushHelper = qBrush; // deprecated initialize.selections = qBrush; /* harmony default export */ __webpack_exports__["a"] = (initialize); //# sourceMappingURL=picasso-q.esm.js.map /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(33))) /***/ }), /* 74 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* WEBPACK VAR INJECTION */(function(global) {/** * A collection of shims that provide minimal functionality of the ES6 collections. * * These implementations are not meant to be used outside of the ResizeObserver * modules as they cover only a limited range of use cases. */ /* eslint-disable require-jsdoc, valid-jsdoc */ var MapShim = (function () { if (typeof Map !== 'undefined') { return Map; } /** * Returns index in provided array that matches the specified key. * * @param {Array} arr * @param {*} key * @returns {number} */ function getIndex(arr, key) { var result = -1; arr.some(function (entry, index) { if (entry[0] === key) { result = index; return true; } return false; }); return result; } return /** @class */ (function () { function class_1() { this.__entries__ = []; } Object.defineProperty(class_1.prototype, "size", { /** * @returns {boolean} */ get: function () { return this.__entries__.length; }, enumerable: true, configurable: true }); /** * @param {*} key * @returns {*} */ class_1.prototype.get = function (key) { var index = getIndex(this.__entries__, key); var entry = this.__entries__[index]; return entry && entry[1]; }; /** * @param {*} key * @param {*} value * @returns {void} */ class_1.prototype.set = function (key, value) { var index = getIndex(this.__entries__, key); if (~index) { this.__entries__[index][1] = value; } else { this.__entries__.push([key, value]); } }; /** * @param {*} key * @returns {void} */ class_1.prototype.delete = function (key) { var entries = this.__entries__; var index = getIndex(entries, key); if (~index) { entries.splice(index, 1); } }; /** * @param {*} key * @returns {void} */ class_1.prototype.has = function (key) { return !!~getIndex(this.__entries__, key); }; /** * @returns {void} */ class_1.prototype.clear = function () { this.__entries__.splice(0); }; /** * @param {Function} callback * @param {*} [ctx=null] * @returns {void} */ class_1.prototype.forEach = function (callback, ctx) { if (ctx === void 0) { ctx = null; } for (var _i = 0, _a = this.__entries__; _i < _a.length; _i++) { var entry = _a[_i]; callback.call(ctx, entry[1], entry[0]); } }; return class_1; }()); })(); /** * Detects whether window and document objects are available in current environment. */ var isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined' && window.document === document; // Returns global object of a current environment. var global$1 = (function () { if (typeof global !== 'undefined' && global.Math === Math) { return global; } if (typeof self !== 'undefined' && self.Math === Math) { return self; } if (typeof window !== 'undefined' && window.Math === Math) { return window; } // eslint-disable-next-line no-new-func return Function('return this')(); })(); /** * A shim for the requestAnimationFrame which falls back to the setTimeout if * first one is not supported. * * @returns {number} Requests' identifier. */ var requestAnimationFrame$1 = (function () { if (typeof requestAnimationFrame === 'function') { // It's required to use a bounded function because IE sometimes throws // an "Invalid calling object" error if rAF is invoked without the global // object on the left hand side. return requestAnimationFrame.bind(global$1); } return function (callback) { return setTimeout(function () { return callback(Date.now()); }, 1000 / 60); }; })(); // Defines minimum timeout before adding a trailing call. var trailingTimeout = 2; /** * Creates a wrapper function which ensures that provided callback will be * invoked only once during the specified delay period. * * @param {Function} callback - Function to be invoked after the delay period. * @param {number} delay - Delay after which to invoke callback. * @returns {Function} */ function throttle (callback, delay) { var leadingCall = false, trailingCall = false, lastCallTime = 0; /** * Invokes the original callback function and schedules new invocation if * the "proxy" was called during current request. * * @returns {void} */ function resolvePending() { if (leadingCall) { leadingCall = false; callback(); } if (trailingCall) { proxy(); } } /** * Callback invoked after the specified delay. It will further postpone * invocation of the original function delegating it to the * requestAnimationFrame. * * @returns {void} */ function timeoutCallback() { requestAnimationFrame$1(resolvePending); } /** * Schedules invocation of the original function. * * @returns {void} */ function proxy() { var timeStamp = Date.now(); if (leadingCall) { // Reject immediately following calls. if (timeStamp - lastCallTime < trailingTimeout) { return; } // Schedule new call to be in invoked when the pending one is resolved. // This is important for "transitions" which never actually start // immediately so there is a chance that we might miss one if change // happens amids the pending invocation. trailingCall = true; } else { leadingCall = true; trailingCall = false; setTimeout(timeoutCallback, delay); } lastCallTime = timeStamp; } return proxy; } // Minimum delay before invoking the update of observers. var REFRESH_DELAY = 20; // A list of substrings of CSS properties used to find transition events that // might affect dimensions of observed elements. var transitionKeys = ['top', 'right', 'bottom', 'left', 'width', 'height', 'size', 'weight']; // Check if MutationObserver is available. var mutationObserverSupported = typeof MutationObserver !== 'undefined'; /** * Singleton controller class which handles updates of ResizeObserver instances. */ var ResizeObserverController = /** @class */ (function () { /** * Creates a new instance of ResizeObserverController. * * @private */ function ResizeObserverController() { /** * Indicates whether DOM listeners have been added. * * @private {boolean} */ this.connected_ = false; /** * Tells that controller has subscribed for Mutation Events. * * @private {boolean} */ this.mutationEventsAdded_ = false; /** * Keeps reference to the instance of MutationObserver. * * @private {MutationObserver} */ this.mutationsObserver_ = null; /** * A list of connected observers. * * @private {Array} */ this.observers_ = []; this.onTransitionEnd_ = this.onTransitionEnd_.bind(this); this.refresh = throttle(this.refresh.bind(this), REFRESH_DELAY); } /** * Adds observer to observers list. * * @param {ResizeObserverSPI} observer - Observer to be added. * @returns {void} */ ResizeObserverController.prototype.addObserver = function (observer) { if (!~this.observers_.indexOf(observer)) { this.observers_.push(observer); } // Add listeners if they haven't been added yet. if (!this.connected_) { this.connect_(); } }; /** * Removes observer from observers list. * * @param {ResizeObserverSPI} observer - Observer to be removed. * @returns {void} */ ResizeObserverController.prototype.removeObserver = function (observer) { var observers = this.observers_; var index = observers.indexOf(observer); // Remove observer if it's present in registry. if (~index) { observers.splice(index, 1); } // Remove listeners if controller has no connected observers. if (!observers.length && this.connected_) { this.disconnect_(); } }; /** * Invokes the update of observers. It will continue running updates insofar * it detects changes. * * @returns {void} */ ResizeObserverController.prototype.refresh = function () { var changesDetected = this.updateObservers_(); // Continue running updates if changes have been detected as there might // be future ones caused by CSS transitions. if (changesDetected) { this.refresh(); } }; /** * Updates every observer from observers list and notifies them of queued * entries. * * @private * @returns {boolean} Returns "true" if any observer has detected changes in * dimensions of it's elements. */ ResizeObserverController.prototype.updateObservers_ = function () { // Collect observers that have active observations. var activeObservers = this.observers_.filter(function (observer) { return observer.gatherActive(), observer.hasActive(); }); // Deliver notifications in a separate cycle in order to avoid any // collisions between observers, e.g. when multiple instances of // ResizeObserver are tracking the same element and the callback of one // of them changes content dimensions of the observed target. Sometimes // this may result in notifications being blocked for the rest of observers. activeObservers.forEach(function (observer) { return observer.broadcastActive(); }); return activeObservers.length > 0; }; /** * Initializes DOM listeners. * * @private * @returns {void} */ ResizeObserverController.prototype.connect_ = function () { // Do nothing if running in a non-browser environment or if listeners // have been already added. if (!isBrowser || this.connected_) { return; } // Subscription to the "Transitionend" event is used as a workaround for // delayed transitions. This way it's possible to capture at least the // final state of an element. document.addEventListener('transitionend', this.onTransitionEnd_); window.addEventListener('resize', this.refresh); if (mutationObserverSupported) { this.mutationsObserver_ = new MutationObserver(this.refresh); this.mutationsObserver_.observe(document, { attributes: true, childList: true, characterData: true, subtree: true }); } else { document.addEventListener('DOMSubtreeModified', this.refresh); this.mutationEventsAdded_ = true; } this.connected_ = true; }; /** * Removes DOM listeners. * * @private * @returns {void} */ ResizeObserverController.prototype.disconnect_ = function () { // Do nothing if running in a non-browser environment or if listeners // have been already removed. if (!isBrowser || !this.connected_) { return; } document.removeEventListener('transitionend', this.onTransitionEnd_); window.removeEventListener('resize', this.refresh); if (this.mutationsObserver_) { this.mutationsObserver_.disconnect(); } if (this.mutationEventsAdded_) { document.removeEventListener('DOMSubtreeModified', this.refresh); } this.mutationsObserver_ = null; this.mutationEventsAdded_ = false; this.connected_ = false; }; /** * "Transitionend" event handler. * * @private * @param {TransitionEvent} event * @returns {void} */ ResizeObserverController.prototype.onTransitionEnd_ = function (_a) { var _b = _a.propertyName, propertyName = _b === void 0 ? '' : _b; // Detect whether transition may affect dimensions of an element. var isReflowProperty = transitionKeys.some(function (key) { return !!~propertyName.indexOf(key); }); if (isReflowProperty) { this.refresh(); } }; /** * Returns instance of the ResizeObserverController. * * @returns {ResizeObserverController} */ ResizeObserverController.getInstance = function () { if (!this.instance_) { this.instance_ = new ResizeObserverController(); } return this.instance_; }; /** * Holds reference to the controller's instance. * * @private {ResizeObserverController} */ ResizeObserverController.instance_ = null; return ResizeObserverController; }()); /** * Defines non-writable/enumerable properties of the provided target object. * * @param {Object} target - Object for which to define properties. * @param {Object} props - Properties to be defined. * @returns {Object} Target object. */ var defineConfigurable = (function (target, props) { for (var _i = 0, _a = Object.keys(props); _i < _a.length; _i++) { var key = _a[_i]; Object.defineProperty(target, key, { value: props[key], enumerable: false, writable: false, configurable: true }); } return target; }); /** * Returns the global object associated with provided element. * * @param {Object} target * @returns {Object} */ var getWindowOf = (function (target) { // Assume that the element is an instance of Node, which means that it // has the "ownerDocument" property from which we can retrieve a // corresponding global object. var ownerGlobal = target && target.ownerDocument && target.ownerDocument.defaultView; // Return the local global object if it's not possible extract one from // provided element. return ownerGlobal || global$1; }); // Placeholder of an empty content rectangle. var emptyRect = createRectInit(0, 0, 0, 0); /** * Converts provided string to a number. * * @param {number|string} value * @returns {number} */ function toFloat(value) { return parseFloat(value) || 0; } /** * Extracts borders size from provided styles. * * @param {CSSStyleDeclaration} styles * @param {...string} positions - Borders positions (top, right, ...) * @returns {number} */ function getBordersSize(styles) { var positions = []; for (var _i = 1; _i < arguments.length; _i++) { positions[_i - 1] = arguments[_i]; } return positions.reduce(function (size, position) { var value = styles['border-' + position + '-width']; return size + toFloat(value); }, 0); } /** * Extracts paddings sizes from provided styles. * * @param {CSSStyleDeclaration} styles * @returns {Object} Paddings box. */ function getPaddings(styles) { var positions = ['top', 'right', 'bottom', 'left']; var paddings = {}; for (var _i = 0, positions_1 = positions; _i < positions_1.length; _i++) { var position = positions_1[_i]; var value = styles['padding-' + position]; paddings[position] = toFloat(value); } return paddings; } /** * Calculates content rectangle of provided SVG element. * * @param {SVGGraphicsElement} target - Element content rectangle of which needs * to be calculated. * @returns {DOMRectInit} */ function getSVGContentRect(target) { var bbox = target.getBBox(); return createRectInit(0, 0, bbox.width, bbox.height); } /** * Calculates content rectangle of provided HTMLElement. * * @param {HTMLElement} target - Element for which to calculate the content rectangle. * @returns {DOMRectInit} */ function getHTMLElementContentRect(target) { // Client width & height properties can't be // used exclusively as they provide rounded values. var clientWidth = target.clientWidth, clientHeight = target.clientHeight; // By this condition we can catch all non-replaced inline, hidden and // detached elements. Though elements with width & height properties less // than 0.5 will be discarded as well. // // Without it we would need to implement separate methods for each of // those cases and it's not possible to perform a precise and performance // effective test for hidden elements. E.g. even jQuery's ':visible' filter // gives wrong results for elements with width & height less than 0.5. if (!clientWidth && !clientHeight) { return emptyRect; } var styles = getWindowOf(target).getComputedStyle(target); var paddings = getPaddings(styles); var horizPad = paddings.left + paddings.right; var vertPad = paddings.top + paddings.bottom; // Computed styles of width & height are being used because they are the // only dimensions available to JS that contain non-rounded values. It could // be possible to utilize the getBoundingClientRect if only it's data wasn't // affected by CSS transformations let alone paddings, borders and scroll bars. var width = toFloat(styles.width), height = toFloat(styles.height); // Width & height include paddings and borders when the 'border-box' box // model is applied (except for IE). if (styles.boxSizing === 'border-box') { // Following conditions are required to handle Internet Explorer which // doesn't include paddings and borders to computed CSS dimensions. // // We can say that if CSS dimensions + paddings are equal to the "client" // properties then it's either IE, and thus we don't need to subtract // anything, or an element merely doesn't have paddings/borders styles. if (Math.round(width + horizPad) !== clientWidth) { width -= getBordersSize(styles, 'left', 'right') + horizPad; } if (Math.round(height + vertPad) !== clientHeight) { height -= getBordersSize(styles, 'top', 'bottom') + vertPad; } } // Following steps can't be applied to the document's root element as its // client[Width/Height] properties represent viewport area of the window. // Besides, it's as well not necessary as the itself neither has // rendered scroll bars nor it can be clipped. if (!isDocumentElement(target)) { // In some browsers (only in Firefox, actually) CSS width & height // include scroll bars size which can be removed at this step as scroll // bars are the only difference between rounded dimensions + paddings // and "client" properties, though that is not always true in Chrome. var vertScrollbar = Math.round(width + horizPad) - clientWidth; var horizScrollbar = Math.round(height + vertPad) - clientHeight; // Chrome has a rather weird rounding of "client" properties. // E.g. for an element with content width of 314.2px it sometimes gives // the client width of 315px and for the width of 314.7px it may give // 314px. And it doesn't happen all the time. So just ignore this delta // as a non-relevant. if (Math.abs(vertScrollbar) !== 1) { width -= vertScrollbar; } if (Math.abs(horizScrollbar) !== 1) { height -= horizScrollbar; } } return createRectInit(paddings.left, paddings.top, width, height); } /** * Checks whether provided element is an instance of the SVGGraphicsElement. * * @param {Element} target - Element to be checked. * @returns {boolean} */ var isSVGGraphicsElement = (function () { // Some browsers, namely IE and Edge, don't have the SVGGraphicsElement // interface. if (typeof SVGGraphicsElement !== 'undefined') { return function (target) { return target instanceof getWindowOf(target).SVGGraphicsElement; }; } // If it's so, then check that element is at least an instance of the // SVGElement and that it has the "getBBox" method. // eslint-disable-next-line no-extra-parens return function (target) { return (target instanceof getWindowOf(target).SVGElement && typeof target.getBBox === 'function'); }; })(); /** * Checks whether provided element is a document element (). * * @param {Element} target - Element to be checked. * @returns {boolean} */ function isDocumentElement(target) { return target === getWindowOf(target).document.documentElement; } /** * Calculates an appropriate content rectangle for provided html or svg element. * * @param {Element} target - Element content rectangle of which needs to be calculated. * @returns {DOMRectInit} */ function getContentRect(target) { if (!isBrowser) { return emptyRect; } if (isSVGGraphicsElement(target)) { return getSVGContentRect(target); } return getHTMLElementContentRect(target); } /** * Creates rectangle with an interface of the DOMRectReadOnly. * Spec: https://drafts.fxtf.org/geometry/#domrectreadonly * * @param {DOMRectInit} rectInit - Object with rectangle's x/y coordinates and dimensions. * @returns {DOMRectReadOnly} */ function createReadOnlyRect(_a) { var x = _a.x, y = _a.y, width = _a.width, height = _a.height; // If DOMRectReadOnly is available use it as a prototype for the rectangle. var Constr = typeof DOMRectReadOnly !== 'undefined' ? DOMRectReadOnly : Object; var rect = Object.create(Constr.prototype); // Rectangle's properties are not writable and non-enumerable. defineConfigurable(rect, { x: x, y: y, width: width, height: height, top: y, right: x + width, bottom: height + y, left: x }); return rect; } /** * Creates DOMRectInit object based on the provided dimensions and the x/y coordinates. * Spec: https://drafts.fxtf.org/geometry/#dictdef-domrectinit * * @param {number} x - X coordinate. * @param {number} y - Y coordinate. * @param {number} width - Rectangle's width. * @param {number} height - Rectangle's height. * @returns {DOMRectInit} */ function createRectInit(x, y, width, height) { return { x: x, y: y, width: width, height: height }; } /** * Class that is responsible for computations of the content rectangle of * provided DOM element and for keeping track of it's changes. */ var ResizeObservation = /** @class */ (function () { /** * Creates an instance of ResizeObservation. * * @param {Element} target - Element to be observed. */ function ResizeObservation(target) { /** * Broadcasted width of content rectangle. * * @type {number} */ this.broadcastWidth = 0; /** * Broadcasted height of content rectangle. * * @type {number} */ this.broadcastHeight = 0; /** * Reference to the last observed content rectangle. * * @private {DOMRectInit} */ this.contentRect_ = createRectInit(0, 0, 0, 0); this.target = target; } /** * Updates content rectangle and tells whether it's width or height properties * have changed since the last broadcast. * * @returns {boolean} */ ResizeObservation.prototype.isActive = function () { var rect = getContentRect(this.target); this.contentRect_ = rect; return (rect.width !== this.broadcastWidth || rect.height !== this.broadcastHeight); }; /** * Updates 'broadcastWidth' and 'broadcastHeight' properties with a data * from the corresponding properties of the last observed content rectangle. * * @returns {DOMRectInit} Last observed content rectangle. */ ResizeObservation.prototype.broadcastRect = function () { var rect = this.contentRect_; this.broadcastWidth = rect.width; this.broadcastHeight = rect.height; return rect; }; return ResizeObservation; }()); var ResizeObserverEntry = /** @class */ (function () { /** * Creates an instance of ResizeObserverEntry. * * @param {Element} target - Element that is being observed. * @param {DOMRectInit} rectInit - Data of the element's content rectangle. */ function ResizeObserverEntry(target, rectInit) { var contentRect = createReadOnlyRect(rectInit); // According to the specification following properties are not writable // and are also not enumerable in the native implementation. // // Property accessors are not being used as they'd require to define a // private WeakMap storage which may cause memory leaks in browsers that // don't support this type of collections. defineConfigurable(this, { target: target, contentRect: contentRect }); } return ResizeObserverEntry; }()); var ResizeObserverSPI = /** @class */ (function () { /** * Creates a new instance of ResizeObserver. * * @param {ResizeObserverCallback} callback - Callback function that is invoked * when one of the observed elements changes it's content dimensions. * @param {ResizeObserverController} controller - Controller instance which * is responsible for the updates of observer. * @param {ResizeObserver} callbackCtx - Reference to the public * ResizeObserver instance which will be passed to callback function. */ function ResizeObserverSPI(callback, controller, callbackCtx) { /** * Collection of resize observations that have detected changes in dimensions * of elements. * * @private {Array} */ this.activeObservations_ = []; /** * Registry of the ResizeObservation instances. * * @private {Map} */ this.observations_ = new MapShim(); if (typeof callback !== 'function') { throw new TypeError('The callback provided as parameter 1 is not a function.'); } this.callback_ = callback; this.controller_ = controller; this.callbackCtx_ = callbackCtx; } /** * Starts observing provided element. * * @param {Element} target - Element to be observed. * @returns {void} */ ResizeObserverSPI.prototype.observe = function (target) { if (!arguments.length) { throw new TypeError('1 argument required, but only 0 present.'); } // Do nothing if current environment doesn't have the Element interface. if (typeof Element === 'undefined' || !(Element instanceof Object)) { return; } if (!(target instanceof getWindowOf(target).Element)) { throw new TypeError('parameter 1 is not of type "Element".'); } var observations = this.observations_; // Do nothing if element is already being observed. if (observations.has(target)) { return; } observations.set(target, new ResizeObservation(target)); this.controller_.addObserver(this); // Force the update of observations. this.controller_.refresh(); }; /** * Stops observing provided element. * * @param {Element} target - Element to stop observing. * @returns {void} */ ResizeObserverSPI.prototype.unobserve = function (target) { if (!arguments.length) { throw new TypeError('1 argument required, but only 0 present.'); } // Do nothing if current environment doesn't have the Element interface. if (typeof Element === 'undefined' || !(Element instanceof Object)) { return; } if (!(target instanceof getWindowOf(target).Element)) { throw new TypeError('parameter 1 is not of type "Element".'); } var observations = this.observations_; // Do nothing if element is not being observed. if (!observations.has(target)) { return; } observations.delete(target); if (!observations.size) { this.controller_.removeObserver(this); } }; /** * Stops observing all elements. * * @returns {void} */ ResizeObserverSPI.prototype.disconnect = function () { this.clearActive(); this.observations_.clear(); this.controller_.removeObserver(this); }; /** * Collects observation instances the associated element of which has changed * it's content rectangle. * * @returns {void} */ ResizeObserverSPI.prototype.gatherActive = function () { var _this = this; this.clearActive(); this.observations_.forEach(function (observation) { if (observation.isActive()) { _this.activeObservations_.push(observation); } }); }; /** * Invokes initial callback function with a list of ResizeObserverEntry * instances collected from active resize observations. * * @returns {void} */ ResizeObserverSPI.prototype.broadcastActive = function () { // Do nothing if observer doesn't have active observations. if (!this.hasActive()) { return; } var ctx = this.callbackCtx_; // Create ResizeObserverEntry instance for every active observation. var entries = this.activeObservations_.map(function (observation) { return new ResizeObserverEntry(observation.target, observation.broadcastRect()); }); this.callback_.call(ctx, entries, ctx); this.clearActive(); }; /** * Clears the collection of active observations. * * @returns {void} */ ResizeObserverSPI.prototype.clearActive = function () { this.activeObservations_.splice(0); }; /** * Tells whether observer has active observations. * * @returns {boolean} */ ResizeObserverSPI.prototype.hasActive = function () { return this.activeObservations_.length > 0; }; return ResizeObserverSPI; }()); // Registry of internal observers. If WeakMap is not available use current shim // for the Map collection as it has all required methods and because WeakMap // can't be fully polyfilled anyway. var observers = typeof WeakMap !== 'undefined' ? new WeakMap() : new MapShim(); /** * ResizeObserver API. Encapsulates the ResizeObserver SPI implementation * exposing only those methods and properties that are defined in the spec. */ var ResizeObserver = /** @class */ (function () { /** * Creates a new instance of ResizeObserver. * * @param {ResizeObserverCallback} callback - Callback that is invoked when * dimensions of the observed elements change. */ function ResizeObserver(callback) { if (!(this instanceof ResizeObserver)) { throw new TypeError('Cannot call a class as a function.'); } if (!arguments.length) { throw new TypeError('1 argument required, but only 0 present.'); } var controller = ResizeObserverController.getInstance(); var observer = new ResizeObserverSPI(callback, controller, this); observers.set(this, observer); } return ResizeObserver; }()); // Expose public methods of ResizeObserver. [ 'observe', 'unobserve', 'disconnect' ].forEach(function (method) { ResizeObserver.prototype[method] = function () { var _a; return (_a = observers.get(this))[method].apply(_a, arguments); }; }); var index = (function () { // Export existing implementation if available. if (typeof global$1.ResizeObserver !== 'undefined') { return global$1.ResizeObserver; } return ResizeObserver; })(); /* harmony default export */ __webpack_exports__["a"] = (index); /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(33))) /***/ }), /* 75 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var _interopRequireDefault = __webpack_require__(34); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _react = _interopRequireDefault(__webpack_require__(0)); var _createSvgIcon = _interopRequireDefault(__webpack_require__(44)); var _default = (0, _createSvgIcon.default)(_react.default.createElement("path", { d: "M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z" }), 'Clear'); exports.default = _default; /***/ }), /* 76 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; // EXTERNAL MODULE: ./node_modules/@material-ui/core/node_modules/@babel/runtime/helpers/esm/defineProperty.js var defineProperty = __webpack_require__(22); // EXTERNAL MODULE: ./node_modules/@material-ui/core/node_modules/@babel/runtime/helpers/esm/objectWithoutProperties.js + 1 modules var objectWithoutProperties = __webpack_require__(4); // EXTERNAL MODULE: ./node_modules/@material-ui/utils/esm/deepmerge.js + 2 modules var deepmerge = __webpack_require__(158); // EXTERNAL MODULE: ./node_modules/@material-ui/core/node_modules/@babel/runtime/helpers/esm/extends.js var esm_extends = __webpack_require__(2); // CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/styles/createBreakpoints.js // Sorted ASC by size. That's important. // It can't be configured as it's used statically for propTypes. var keys = ['xs', 'sm', 'md', 'lg', 'xl']; // Keep in mind that @media is inclusive by the CSS specification. function createBreakpoints(breakpoints) { var _breakpoints$values = breakpoints.values, values = _breakpoints$values === void 0 ? { xs: 0, sm: 600, md: 960, lg: 1280, xl: 1920 } : _breakpoints$values, _breakpoints$unit = breakpoints.unit, unit = _breakpoints$unit === void 0 ? 'px' : _breakpoints$unit, _breakpoints$step = breakpoints.step, step = _breakpoints$step === void 0 ? 5 : _breakpoints$step, other = Object(objectWithoutProperties["a" /* default */])(breakpoints, ["values", "unit", "step"]); function up(key) { var value = typeof values[key] === 'number' ? values[key] : key; return "@media (min-width:".concat(value).concat(unit, ")"); } function down(key) { var endIndex = keys.indexOf(key) + 1; var upperbound = values[keys[endIndex]]; if (endIndex === keys.length) { // xl down applies to all sizes return up('xs'); } var value = typeof upperbound === 'number' && endIndex > 0 ? upperbound : key; return "@media (max-width:".concat(value - step / 100).concat(unit, ")"); } function between(start, end) { var endIndex = keys.indexOf(end); if (endIndex === keys.length - 1) { return up(start); } return "@media (min-width:".concat(typeof values[start] === 'number' ? values[start] : start).concat(unit, ") and ") + "(max-width:".concat((endIndex !== -1 && typeof values[keys[endIndex + 1]] === 'number' ? values[keys[endIndex + 1]] : end) - step / 100).concat(unit, ")"); } function only(key) { return between(key, key); } function width(key) { return values[key]; } return Object(esm_extends["a" /* default */])({ keys: keys, values: values, up: up, down: down, between: between, only: only, width: width }, other); } // CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/styles/createMixins.js function createMixins(breakpoints, spacing, mixins) { var _toolbar; return Object(esm_extends["a" /* default */])({ gutters: function gutters() { var styles = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; // To deprecate in v4.1 // warning( // false, // [ // 'Material-UI: theme.mixins.gutters() is deprecated.', // 'You can use the source of the mixin directly:', // ` // paddingLeft: theme.spacing(2), // paddingRight: theme.spacing(2), // [theme.breakpoints.up('sm')]: { // paddingLeft: theme.spacing(3), // paddingRight: theme.spacing(3), // }, // `, // ].join('\n'), // ); return Object(esm_extends["a" /* default */])({ paddingLeft: spacing(2), paddingRight: spacing(2) }, styles, Object(defineProperty["a" /* default */])({}, breakpoints.up('sm'), Object(esm_extends["a" /* default */])({ paddingLeft: spacing(3), paddingRight: spacing(3) }, styles[breakpoints.up('sm')]))); }, toolbar: (_toolbar = { minHeight: 56 }, Object(defineProperty["a" /* default */])(_toolbar, "".concat(breakpoints.up('xs'), " and (orientation: landscape)"), { minHeight: 48 }), Object(defineProperty["a" /* default */])(_toolbar, breakpoints.up('sm'), { minHeight: 64 }), _toolbar) }, mixins); } // CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/colors/common.js var common = { black: '#000', white: '#fff' }; /* harmony default export */ var colors_common = (common); // CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/colors/grey.js var grey = { 50: '#fafafa', 100: '#f5f5f5', 200: '#eeeeee', 300: '#e0e0e0', 400: '#bdbdbd', 500: '#9e9e9e', 600: '#757575', 700: '#616161', 800: '#424242', 900: '#212121', A100: '#d5d5d5', A200: '#aaaaaa', A400: '#303030', A700: '#616161' }; /* harmony default export */ var colors_grey = (grey); // CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/colors/indigo.js var indigo = { 50: '#e8eaf6', 100: '#c5cae9', 200: '#9fa8da', 300: '#7986cb', 400: '#5c6bc0', 500: '#3f51b5', 600: '#3949ab', 700: '#303f9f', 800: '#283593', 900: '#1a237e', A100: '#8c9eff', A200: '#536dfe', A400: '#3d5afe', A700: '#304ffe' }; /* harmony default export */ var colors_indigo = (indigo); // CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/colors/pink.js var pink = { 50: '#fce4ec', 100: '#f8bbd0', 200: '#f48fb1', 300: '#f06292', 400: '#ec407a', 500: '#e91e63', 600: '#d81b60', 700: '#c2185b', 800: '#ad1457', 900: '#880e4f', A100: '#ff80ab', A200: '#ff4081', A400: '#f50057', A700: '#c51162' }; /* harmony default export */ var colors_pink = (pink); // CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/colors/red.js var red = { 50: '#ffebee', 100: '#ffcdd2', 200: '#ef9a9a', 300: '#e57373', 400: '#ef5350', 500: '#f44336', 600: '#e53935', 700: '#d32f2f', 800: '#c62828', 900: '#b71c1c', A100: '#ff8a80', A200: '#ff5252', A400: '#ff1744', A700: '#d50000' }; /* harmony default export */ var colors_red = (red); // CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/colors/orange.js var orange = { 50: '#fff3e0', 100: '#ffe0b2', 200: '#ffcc80', 300: '#ffb74d', 400: '#ffa726', 500: '#ff9800', 600: '#fb8c00', 700: '#f57c00', 800: '#ef6c00', 900: '#e65100', A100: '#ffd180', A200: '#ffab40', A400: '#ff9100', A700: '#ff6d00' }; /* harmony default export */ var colors_orange = (orange); // CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/colors/blue.js var blue = { 50: '#e3f2fd', 100: '#bbdefb', 200: '#90caf9', 300: '#64b5f6', 400: '#42a5f5', 500: '#2196f3', 600: '#1e88e5', 700: '#1976d2', 800: '#1565c0', 900: '#0d47a1', A100: '#82b1ff', A200: '#448aff', A400: '#2979ff', A700: '#2962ff' }; /* harmony default export */ var colors_blue = (blue); // CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/colors/green.js var green = { 50: '#e8f5e9', 100: '#c8e6c9', 200: '#a5d6a7', 300: '#81c784', 400: '#66bb6a', 500: '#4caf50', 600: '#43a047', 700: '#388e3c', 800: '#2e7d32', 900: '#1b5e20', A100: '#b9f6ca', A200: '#69f0ae', A400: '#00e676', A700: '#00c853' }; /* harmony default export */ var colors_green = (green); // EXTERNAL MODULE: ./node_modules/@material-ui/core/esm/styles/colorManipulator.js var colorManipulator = __webpack_require__(11); // CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/styles/createPalette.js var light = { // The colors used to style the text. text: { // The most important text. primary: 'rgba(0, 0, 0, 0.87)', // Secondary text. secondary: 'rgba(0, 0, 0, 0.54)', // Disabled text have even lower visual prominence. disabled: 'rgba(0, 0, 0, 0.38)', // Text hints. hint: 'rgba(0, 0, 0, 0.38)' }, // The color used to divide different elements. divider: 'rgba(0, 0, 0, 0.12)', // The background colors used to style the surfaces. // Consistency between these values is important. background: { paper: colors_common.white, default: colors_grey[50] }, // The colors used to style the action elements. action: { // The color of an active action like an icon button. active: 'rgba(0, 0, 0, 0.54)', // The color of an hovered action. hover: 'rgba(0, 0, 0, 0.04)', hoverOpacity: 0.04, // The color of a selected action. selected: 'rgba(0, 0, 0, 0.08)', selectedOpacity: 0.08, // The color of a disabled action. disabled: 'rgba(0, 0, 0, 0.26)', // The background color of a disabled action. disabledBackground: 'rgba(0, 0, 0, 0.12)', disabledOpacity: 0.38, focus: 'rgba(0, 0, 0, 0.12)', focusOpacity: 0.12, activatedOpaciy: 0.12 } }; var dark = { text: { primary: colors_common.white, secondary: 'rgba(255, 255, 255, 0.7)', disabled: 'rgba(255, 255, 255, 0.5)', hint: 'rgba(255, 255, 255, 0.5)', icon: 'rgba(255, 255, 255, 0.5)' }, divider: 'rgba(255, 255, 255, 0.12)', background: { paper: colors_grey[800], default: '#303030' }, action: { active: colors_common.white, hover: 'rgba(255, 255, 255, 0.08)', hoverOpacity: 0.08, selected: 'rgba(255, 255, 255, 0.16)', selectedOpacity: 0.16, disabled: 'rgba(255, 255, 255, 0.3)', disabledBackground: 'rgba(255, 255, 255, 0.12)', disabledOpacity: 0.38, focus: 'rgba(255, 255, 255, 0.12)', focusOpacity: 0.12, activatedOpaciy: 0.24 } }; function addLightOrDark(intent, direction, shade, tonalOffset) { if (!intent[direction]) { if (intent.hasOwnProperty(shade)) { intent[direction] = intent[shade]; } else if (direction === 'light') { intent.light = Object(colorManipulator["d" /* lighten */])(intent.main, tonalOffset); } else if (direction === 'dark') { intent.dark = Object(colorManipulator["a" /* darken */])(intent.main, tonalOffset * 1.5); } } } function createPalette(palette) { var _palette$primary = palette.primary, primary = _palette$primary === void 0 ? { light: colors_indigo[300], main: colors_indigo[500], dark: colors_indigo[700] } : _palette$primary, _palette$secondary = palette.secondary, secondary = _palette$secondary === void 0 ? { light: colors_pink.A200, main: colors_pink.A400, dark: colors_pink.A700 } : _palette$secondary, _palette$error = palette.error, error = _palette$error === void 0 ? { light: colors_red[300], main: colors_red[500], dark: colors_red[700] } : _palette$error, _palette$warning = palette.warning, warning = _palette$warning === void 0 ? { light: colors_orange[300], main: colors_orange[500], dark: colors_orange[700] } : _palette$warning, _palette$info = palette.info, info = _palette$info === void 0 ? { light: colors_blue[300], main: colors_blue[500], dark: colors_blue[700] } : _palette$info, _palette$success = palette.success, success = _palette$success === void 0 ? { light: colors_green[300], main: colors_green[500], dark: colors_green[700] } : _palette$success, _palette$type = palette.type, type = _palette$type === void 0 ? 'light' : _palette$type, _palette$contrastThre = palette.contrastThreshold, contrastThreshold = _palette$contrastThre === void 0 ? 3 : _palette$contrastThre, _palette$tonalOffset = palette.tonalOffset, tonalOffset = _palette$tonalOffset === void 0 ? 0.2 : _palette$tonalOffset, other = Object(objectWithoutProperties["a" /* default */])(palette, ["primary", "secondary", "error", "warning", "info", "success", "type", "contrastThreshold", "tonalOffset"]); // Use the same logic as // Bootstrap: https://github.com/twbs/bootstrap/blob/1d6e3710dd447de1a200f29e8fa521f8a0908f70/scss/_functions.scss#L59 // and material-components-web https://github.com/material-components/material-components-web/blob/ac46b8863c4dab9fc22c4c662dc6bd1b65dd652f/packages/mdc-theme/_functions.scss#L54 function getContrastText(background) { if (!background) { throw new TypeError("Material-UI: missing background argument in getContrastText(".concat(background, ").")); } var contrastText = Object(colorManipulator["c" /* getContrastRatio */])(background, dark.text.primary) >= contrastThreshold ? dark.text.primary : light.text.primary; if (false) { var contrast; } return contrastText; } function augmentColor(color) { var mainShade = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 500; var lightShade = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 300; var darkShade = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 700; color = Object(esm_extends["a" /* default */])({}, color); if (!color.main && color[mainShade]) { color.main = color[mainShade]; } if (false) {} addLightOrDark(color, 'light', lightShade, tonalOffset); addLightOrDark(color, 'dark', darkShade, tonalOffset); if (!color.contrastText) { color.contrastText = getContrastText(color.main); } return color; } var types = { dark: dark, light: light }; if (false) {} var paletteOutput = Object(deepmerge["a" /* default */])(Object(esm_extends["a" /* default */])({ // A collection of common colors. common: colors_common, // The palette type, can be light or dark. type: type, // The colors used to represent primary interface elements for a user. primary: augmentColor(primary), // The colors used to represent secondary interface elements for a user. secondary: augmentColor(secondary, 'A400', 'A200', 'A700'), // The colors used to represent interface elements that the user should be made aware of. error: augmentColor(error), // The colors used to represent potentially dangerous actions or important messages. warning: augmentColor(warning), // The colors used to present information to the user that is neutral and not necessarily important. info: augmentColor(info), // The colors used to indicate the successful completion of an action that user triggered. success: augmentColor(success), // The grey colors. grey: colors_grey, // Used by `getContrastText()` to maximize the contrast between // the background and the text. contrastThreshold: contrastThreshold, // Takes a background color and returns the text color that maximizes the contrast. getContrastText: getContrastText, // Generate a rich color object. augmentColor: augmentColor, // Used by the functions below to shift a color's luminance by approximately // two indexes within its tonal palette. // E.g., shift from Red 500 to Red 300 or Red 700. tonalOffset: tonalOffset }, types[type]), other); return paletteOutput; } // CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/styles/createTypography.js function round(value) { return Math.round(value * 1e5) / 1e5; } var caseAllCaps = { textTransform: 'uppercase' }; var defaultFontFamily = '"Roboto", "Helvetica", "Arial", sans-serif'; /** * @see @link{https://material.io/design/typography/the-type-system.html} * @see @link{https://material.io/design/typography/understanding-typography.html} */ function createTypography(palette, typography) { var _ref = typeof typography === 'function' ? typography(palette) : typography, _ref$fontFamily = _ref.fontFamily, fontFamily = _ref$fontFamily === void 0 ? defaultFontFamily : _ref$fontFamily, _ref$fontSize = _ref.fontSize, fontSize = _ref$fontSize === void 0 ? 14 : _ref$fontSize, _ref$fontWeightLight = _ref.fontWeightLight, fontWeightLight = _ref$fontWeightLight === void 0 ? 300 : _ref$fontWeightLight, _ref$fontWeightRegula = _ref.fontWeightRegular, fontWeightRegular = _ref$fontWeightRegula === void 0 ? 400 : _ref$fontWeightRegula, _ref$fontWeightMedium = _ref.fontWeightMedium, fontWeightMedium = _ref$fontWeightMedium === void 0 ? 500 : _ref$fontWeightMedium, _ref$fontWeightBold = _ref.fontWeightBold, fontWeightBold = _ref$fontWeightBold === void 0 ? 700 : _ref$fontWeightBold, _ref$htmlFontSize = _ref.htmlFontSize, htmlFontSize = _ref$htmlFontSize === void 0 ? 16 : _ref$htmlFontSize, allVariants = _ref.allVariants, pxToRem2 = _ref.pxToRem, other = Object(objectWithoutProperties["a" /* default */])(_ref, ["fontFamily", "fontSize", "fontWeightLight", "fontWeightRegular", "fontWeightMedium", "fontWeightBold", "htmlFontSize", "allVariants", "pxToRem"]); if (false) {} var coef = fontSize / 14; var pxToRem = pxToRem2 || function (size) { return "".concat(size / htmlFontSize * coef, "rem"); }; var buildVariant = function buildVariant(fontWeight, size, lineHeight, letterSpacing, casing) { return Object(esm_extends["a" /* default */])({ fontFamily: fontFamily, fontWeight: fontWeight, fontSize: pxToRem(size), // Unitless following https://meyerweb.com/eric/thoughts/2006/02/08/unitless-line-heights/ lineHeight: lineHeight }, fontFamily === defaultFontFamily ? { letterSpacing: "".concat(round(letterSpacing / size), "em") } : {}, {}, casing, {}, allVariants); }; var variants = { h1: buildVariant(fontWeightLight, 96, 1.167, -1.5), h2: buildVariant(fontWeightLight, 60, 1.2, -0.5), h3: buildVariant(fontWeightRegular, 48, 1.167, 0), h4: buildVariant(fontWeightRegular, 34, 1.235, 0.25), h5: buildVariant(fontWeightRegular, 24, 1.334, 0), h6: buildVariant(fontWeightMedium, 20, 1.6, 0.15), subtitle1: buildVariant(fontWeightRegular, 16, 1.75, 0.15), subtitle2: buildVariant(fontWeightMedium, 14, 1.57, 0.1), body1: buildVariant(fontWeightRegular, 16, 1.5, 0.15), body2: buildVariant(fontWeightRegular, 14, 1.43, 0.15), button: buildVariant(fontWeightMedium, 14, 1.75, 0.4, caseAllCaps), caption: buildVariant(fontWeightRegular, 12, 1.66, 0.4), overline: buildVariant(fontWeightRegular, 12, 2.66, 1, caseAllCaps) }; return Object(deepmerge["a" /* default */])(Object(esm_extends["a" /* default */])({ htmlFontSize: htmlFontSize, pxToRem: pxToRem, round: round, // TODO v5: remove fontFamily: fontFamily, fontSize: fontSize, fontWeightLight: fontWeightLight, fontWeightRegular: fontWeightRegular, fontWeightMedium: fontWeightMedium, fontWeightBold: fontWeightBold }, variants), other, { clone: false // No need to clone deep }); } // CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/styles/shadows.js var shadowKeyUmbraOpacity = 0.2; var shadowKeyPenumbraOpacity = 0.14; var shadowAmbientShadowOpacity = 0.12; function createShadow() { return ["".concat(arguments.length <= 0 ? undefined : arguments[0], "px ").concat(arguments.length <= 1 ? undefined : arguments[1], "px ").concat(arguments.length <= 2 ? undefined : arguments[2], "px ").concat(arguments.length <= 3 ? undefined : arguments[3], "px rgba(0,0,0,").concat(shadowKeyUmbraOpacity, ")"), "".concat(arguments.length <= 4 ? undefined : arguments[4], "px ").concat(arguments.length <= 5 ? undefined : arguments[5], "px ").concat(arguments.length <= 6 ? undefined : arguments[6], "px ").concat(arguments.length <= 7 ? undefined : arguments[7], "px rgba(0,0,0,").concat(shadowKeyPenumbraOpacity, ")"), "".concat(arguments.length <= 8 ? undefined : arguments[8], "px ").concat(arguments.length <= 9 ? undefined : arguments[9], "px ").concat(arguments.length <= 10 ? undefined : arguments[10], "px ").concat(arguments.length <= 11 ? undefined : arguments[11], "px rgba(0,0,0,").concat(shadowAmbientShadowOpacity, ")")].join(','); } // Values from https://github.com/material-components/material-components-web/blob/be8747f94574669cb5e7add1a7c54fa41a89cec7/packages/mdc-elevation/_variables.scss var shadows = ['none', createShadow(0, 2, 1, -1, 0, 1, 1, 0, 0, 1, 3, 0), createShadow(0, 3, 1, -2, 0, 2, 2, 0, 0, 1, 5, 0), createShadow(0, 3, 3, -2, 0, 3, 4, 0, 0, 1, 8, 0), createShadow(0, 2, 4, -1, 0, 4, 5, 0, 0, 1, 10, 0), createShadow(0, 3, 5, -1, 0, 5, 8, 0, 0, 1, 14, 0), createShadow(0, 3, 5, -1, 0, 6, 10, 0, 0, 1, 18, 0), createShadow(0, 4, 5, -2, 0, 7, 10, 1, 0, 2, 16, 1), createShadow(0, 5, 5, -3, 0, 8, 10, 1, 0, 3, 14, 2), createShadow(0, 5, 6, -3, 0, 9, 12, 1, 0, 3, 16, 2), createShadow(0, 6, 6, -3, 0, 10, 14, 1, 0, 4, 18, 3), createShadow(0, 6, 7, -4, 0, 11, 15, 1, 0, 4, 20, 3), createShadow(0, 7, 8, -4, 0, 12, 17, 2, 0, 5, 22, 4), createShadow(0, 7, 8, -4, 0, 13, 19, 2, 0, 5, 24, 4), createShadow(0, 7, 9, -4, 0, 14, 21, 2, 0, 5, 26, 4), createShadow(0, 8, 9, -5, 0, 15, 22, 2, 0, 6, 28, 5), createShadow(0, 8, 10, -5, 0, 16, 24, 2, 0, 6, 30, 5), createShadow(0, 8, 11, -5, 0, 17, 26, 2, 0, 6, 32, 5), createShadow(0, 9, 11, -5, 0, 18, 28, 2, 0, 7, 34, 6), createShadow(0, 9, 12, -6, 0, 19, 29, 2, 0, 7, 36, 6), createShadow(0, 10, 13, -6, 0, 20, 31, 3, 0, 8, 38, 7), createShadow(0, 10, 13, -6, 0, 21, 33, 3, 0, 8, 40, 7), createShadow(0, 10, 14, -6, 0, 22, 35, 3, 0, 8, 42, 7), createShadow(0, 11, 14, -7, 0, 23, 36, 3, 0, 9, 44, 8), createShadow(0, 11, 15, -7, 0, 24, 38, 3, 0, 9, 46, 8)]; /* harmony default export */ var styles_shadows = (shadows); // CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/styles/shape.js var shape = { borderRadius: 4 }; /* harmony default export */ var styles_shape = (shape); // CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/styles/createSpacing.js var warnOnce; function createSpacing() { var spacingInput = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 8; // Already transformed. if (spacingInput.mui) { return spacingInput; } // All components align to an 8dp square baseline grid for mobile, tablet, and desktop. // https://material.io/design/layout/understanding-layout.html#pixel-density var transform; if (typeof spacingInput === 'function') { transform = spacingInput; } else { if (false) {} transform = function transform(factor) { if (false) {} return spacingInput * factor; }; } var spacing = function spacing() { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } if (false) {} if (args.length === 0) { return transform(1); } if (args.length === 1) { return transform(args[0]); } return args.map(function (factor) { var output = transform(factor); return typeof output === 'number' ? "".concat(output, "px") : output; }).join(' '); }; // Backward compatibility, to remove in v5. Object.defineProperty(spacing, 'unit', { get: function get() { if (false) {} return spacingInput; } }); spacing.mui = true; return spacing; } // EXTERNAL MODULE: ./node_modules/@material-ui/core/esm/styles/transitions.js var transitions = __webpack_require__(31); // EXTERNAL MODULE: ./node_modules/@material-ui/core/esm/styles/zIndex.js var zIndex = __webpack_require__(35); // CONCATENATED MODULE: ./node_modules/@material-ui/core/esm/styles/createMuiTheme.js function createMuiTheme() { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var _options$breakpoints = options.breakpoints, breakpointsInput = _options$breakpoints === void 0 ? {} : _options$breakpoints, _options$mixins = options.mixins, mixinsInput = _options$mixins === void 0 ? {} : _options$mixins, _options$palette = options.palette, paletteInput = _options$palette === void 0 ? {} : _options$palette, spacingInput = options.spacing, _options$typography = options.typography, typographyInput = _options$typography === void 0 ? {} : _options$typography, other = Object(objectWithoutProperties["a" /* default */])(options, ["breakpoints", "mixins", "palette", "spacing", "typography"]); var palette = createPalette(paletteInput); var breakpoints = createBreakpoints(breakpointsInput); var spacing = createSpacing(spacingInput); var muiTheme = Object(deepmerge["a" /* default */])({ breakpoints: breakpoints, direction: 'ltr', mixins: createMixins(breakpoints, spacing, mixinsInput), overrides: {}, // Inject custom styles palette: palette, props: {}, // Provide default props shadows: styles_shadows, typography: createTypography(palette, typographyInput), spacing: spacing, shape: styles_shape, transitions: transitions["a" /* default */], zIndex: zIndex["a" /* default */] }, other); for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } muiTheme = args.reduce(function (acc, argument) { return Object(deepmerge["a" /* default */])(acc, argument); }, muiTheme); if (false) { var traverse, pseudoClasses; } return muiTheme; } /* harmony default export */ var styles_createMuiTheme = __webpack_exports__["a"] = (createMuiTheme); /***/ }), /* 77 */, /* 78 */, /* 79 */, /* 80 */, /* 81 */, /* 82 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** @license React v16.11.0 * react.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var h=__webpack_require__(52),n="function"===typeof Symbol&&Symbol.for,p=n?Symbol.for("react.element"):60103,q=n?Symbol.for("react.portal"):60106,r=n?Symbol.for("react.fragment"):60107,t=n?Symbol.for("react.strict_mode"):60108,u=n?Symbol.for("react.profiler"):60114,v=n?Symbol.for("react.provider"):60109,w=n?Symbol.for("react.context"):60110,x=n?Symbol.for("react.forward_ref"):60112,y=n?Symbol.for("react.suspense"):60113;n&&Symbol.for("react.suspense_list"); var z=n?Symbol.for("react.memo"):60115,aa=n?Symbol.for("react.lazy"):60116;n&&Symbol.for("react.fundamental");n&&Symbol.for("react.responder");n&&Symbol.for("react.scope");var A="function"===typeof Symbol&&Symbol.iterator; function B(a){for(var b="https://reactjs.org/docs/error-decoder.html?invariant="+a,c=1;cP.length&&P.push(a)} function S(a,b,c,e){var d=typeof a;if("undefined"===d||"boolean"===d)a=null;var g=!1;if(null===a)g=!0;else switch(d){case "string":case "number":g=!0;break;case "object":switch(a.$$typeof){case p:case q:g=!0}}if(g)return c(e,a,""===b?"."+T(a,0):b),1;g=0;b=""===b?".":b+":";if(Array.isArray(a))for(var l=0;lb}return!1}function B(a,b,c,d,e,f){this.acceptsBooleans=2===b||3===b||4===b;this.attributeName=d;this.attributeNamespace=e;this.mustUseProperty=c;this.propertyName=a;this.type=b;this.sanitizeURL=f}var D={}; "children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(a){D[a]=new B(a,0,!1,a,null,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(a){var b=a[0];D[b]=new B(b,1,!1,a[1],null,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(a){D[a]=new B(a,2,!1,a.toLowerCase(),null,!1)}); ["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(a){D[a]=new B(a,2,!1,a,null,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(a){D[a]=new B(a,3,!1,a.toLowerCase(),null,!1)}); ["checked","multiple","muted","selected"].forEach(function(a){D[a]=new B(a,3,!0,a,null,!1)});["capture","download"].forEach(function(a){D[a]=new B(a,4,!1,a,null,!1)});["cols","rows","size","span"].forEach(function(a){D[a]=new B(a,6,!1,a,null,!1)});["rowSpan","start"].forEach(function(a){D[a]=new B(a,5,!1,a.toLowerCase(),null,!1)});var sb=/[\-:]([a-z])/g;function tb(a){return a[1].toUpperCase()} "accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(a){var b=a.replace(sb, tb);D[b]=new B(b,1,!1,a,null,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(a){var b=a.replace(sb,tb);D[b]=new B(b,1,!1,a,"http://www.w3.org/1999/xlink",!1)});["xml:base","xml:lang","xml:space"].forEach(function(a){var b=a.replace(sb,tb);D[b]=new B(b,1,!1,a,"http://www.w3.org/XML/1998/namespace",!1)});["tabIndex","crossOrigin"].forEach(function(a){D[a]=new B(a,1,!1,a.toLowerCase(),null,!1)}); D.xlinkHref=new B("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0);["src","href","action","formAction"].forEach(function(a){D[a]=new B(a,1,!1,a.toLowerCase(),null,!0)});function ub(a){switch(typeof a){case "boolean":case "number":case "object":case "string":case "undefined":return a;default:return""}} function vb(a,b,c,d){var e=D.hasOwnProperty(b)?D[b]:null;var f=null!==e?0===e.type:d?!1:!(2=b.length))throw Error(u(93));b=b[0]}c=b}null==c&&(c="")}a._wrapperState={initialValue:ub(c)}} function Mb(a,b){var c=ub(b.value),d=ub(b.defaultValue);null!=c&&(c=""+c,c!==a.value&&(a.value=c),null==b.defaultValue&&a.defaultValue!==c&&(a.defaultValue=c));null!=d&&(a.defaultValue=""+d)}function Nb(a){var b=a.textContent;b===a._wrapperState.initialValue&&""!==b&&null!==b&&(a.value=b)}var Ob={html:"http://www.w3.org/1999/xhtml",mathml:"http://www.w3.org/1998/Math/MathML",svg:"http://www.w3.org/2000/svg"}; function Pb(a){switch(a){case "svg":return"http://www.w3.org/2000/svg";case "math":return"http://www.w3.org/1998/Math/MathML";default:return"http://www.w3.org/1999/xhtml"}}function Qb(a,b){return null==a||"http://www.w3.org/1999/xhtml"===a?Pb(b):"http://www.w3.org/2000/svg"===a&&"foreignObject"===b?"http://www.w3.org/1999/xhtml":a} var Rb,Sb=function(a){return"undefined"!==typeof MSApp&&MSApp.execUnsafeLocalFunction?function(b,c,d,e){MSApp.execUnsafeLocalFunction(function(){return a(b,c,d,e)})}:a}(function(a,b){if(a.namespaceURI!==Ob.svg||"innerHTML"in a)a.innerHTML=b;else{Rb=Rb||document.createElement("div");Rb.innerHTML=""+b.valueOf().toString()+"";for(b=Rb.firstChild;a.firstChild;)a.removeChild(a.firstChild);for(;b.firstChild;)a.appendChild(b.firstChild)}}); function Tb(a,b){if(b){var c=a.firstChild;if(c&&c===a.lastChild&&3===c.nodeType){c.nodeValue=b;return}}a.textContent=b}function Ub(a,b){var c={};c[a.toLowerCase()]=b.toLowerCase();c["Webkit"+a]="webkit"+b;c["Moz"+a]="moz"+b;return c}var Vb={animationend:Ub("Animation","AnimationEnd"),animationiteration:Ub("Animation","AnimationIteration"),animationstart:Ub("Animation","AnimationStart"),transitionend:Ub("Transition","TransitionEnd")},Wb={},Xb={}; Ya&&(Xb=document.createElement("div").style,"AnimationEvent"in window||(delete Vb.animationend.animation,delete Vb.animationiteration.animation,delete Vb.animationstart.animation),"TransitionEvent"in window||delete Vb.transitionend.transition);function Yb(a){if(Wb[a])return Wb[a];if(!Vb[a])return a;var b=Vb[a],c;for(c in b)if(b.hasOwnProperty(c)&&c in Xb)return Wb[a]=b[c];return a}var Zb=Yb("animationend"),$b=Yb("animationiteration"),ac=Yb("animationstart"),bc=Yb("transitionend"),dc="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange seeked seeking stalled suspend timeupdate volumechange waiting".split(" "); function ec(a){var b=a,c=a;if(a.alternate)for(;b.return;)b=b.return;else{a=b;do b=a,0!==(b.effectTag&1026)&&(c=b.return),a=b.return;while(a)}return 3===b.tag?c:null}function fc(a){if(13===a.tag){var b=a.memoizedState;null===b&&(a=a.alternate,null!==a&&(b=a.memoizedState));if(null!==b)return b.dehydrated}return null}function gc(a){if(ec(a)!==a)throw Error(u(188));} function hc(a){var b=a.alternate;if(!b){b=ec(a);if(null===b)throw Error(u(188));return b!==a?null:a}for(var c=a,d=b;;){var e=c.return;if(null===e)break;var f=e.alternate;if(null===f){d=e.return;if(null!==d){c=d;continue}break}if(e.child===f.child){for(f=e.child;f;){if(f===c)return gc(e),a;if(f===d)return gc(e),b;f=f.sibling}throw Error(u(188));}if(c.return!==d.return)c=e,d=f;else{for(var g=!1,h=e.child;h;){if(h===c){g=!0;c=e;d=f;break}if(h===d){g=!0;d=e;c=f;break}h=h.sibling}if(!g){for(h=f.child;h;){if(h=== c){g=!0;c=f;d=e;break}if(h===d){g=!0;d=f;c=e;break}h=h.sibling}if(!g)throw Error(u(189));}}if(c.alternate!==d)throw Error(u(190));}if(3!==c.tag)throw Error(u(188));return c.stateNode.current===c?a:b}function ic(a){a=hc(a);if(!a)return null;for(var b=a;;){if(5===b.tag||6===b.tag)return b;if(b.child)b.child.return=b,b=b.child;else{if(b===a)break;for(;!b.sibling;){if(!b.return||b.return===a)return null;b=b.return}b.sibling.return=b.return;b=b.sibling}}return null} var jc,kc,lc,mc=!1,nc=[],oc=null,pc=null,qc=null,rc=new Map,sc=new Map,tc=[],uc="mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput close cancel copy cut paste click change contextmenu reset submit".split(" "),vc="focus blur dragenter dragleave mouseover mouseout pointerover pointerout gotpointercapture lostpointercapture".split(" "); function wc(a){var b=xc(a);uc.forEach(function(c){yc(c,a,b)});vc.forEach(function(c){yc(c,a,b)})}function zc(a,b,c,d){return{blockedOn:a,topLevelType:b,eventSystemFlags:c|32,nativeEvent:d}}function Ac(a,b){switch(a){case "focus":case "blur":oc=null;break;case "dragenter":case "dragleave":pc=null;break;case "mouseover":case "mouseout":qc=null;break;case "pointerover":case "pointerout":rc.delete(b.pointerId);break;case "gotpointercapture":case "lostpointercapture":sc.delete(b.pointerId)}} function Bc(a,b,c,d,e){if(null===a||a.nativeEvent!==e)return a=zc(b,c,d,e),null!==b&&(b=Cc(b),null!==b&&kc(b)),a;a.eventSystemFlags|=d;return a}function Dc(a,b,c,d){switch(b){case "focus":return oc=Bc(oc,a,b,c,d),!0;case "dragenter":return pc=Bc(pc,a,b,c,d),!0;case "mouseover":return qc=Bc(qc,a,b,c,d),!0;case "pointerover":var e=d.pointerId;rc.set(e,Bc(rc.get(e)||null,a,b,c,d));return!0;case "gotpointercapture":return e=d.pointerId,sc.set(e,Bc(sc.get(e)||null,a,b,c,d)),!0}return!1} function Ec(a){var b=Fc(a.target);if(null!==b){var c=ec(b);if(null!==c)if(b=c.tag,13===b){if(b=fc(c),null!==b){a.blockedOn=b;q.unstable_runWithPriority(a.priority,function(){lc(c)});return}}else if(3===b&&c.stateNode.hydrate){a.blockedOn=3===c.tag?c.stateNode.containerInfo:null;return}}a.blockedOn=null}function Gc(a){if(null!==a.blockedOn)return!1;var b=Hc(a.topLevelType,a.eventSystemFlags,a.nativeEvent);if(null!==b){var c=Cc(b);null!==c&&kc(c);a.blockedOn=b;return!1}return!0} function Ic(a,b,c){Gc(a)&&c.delete(b)}function Jc(){for(mc=!1;0this.eventPool.length&&this.eventPool.push(a)}function Vc(a){a.eventPool=[];a.getPooled=Wc;a.release=Xc}var Yc=E.extend({animationName:null,elapsedTime:null,pseudoElement:null}),Zc=E.extend({clipboardData:function(a){return"clipboardData"in a?a.clipboardData:window.clipboardData}}),$c=E.extend({view:null,detail:null}),ad=$c.extend({relatedTarget:null}); function bd(a){var b=a.keyCode;"charCode"in a?(a=a.charCode,0===a&&13===b&&(a=13)):a=b;10===a&&(a=13);return 32<=a||13===a?a:0} var cd={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},ed={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4", 116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},fd={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function gd(a){var b=this.nativeEvent;return b.getModifierState?b.getModifierState(a):(a=fd[a])?!!b[a]:!1}function hd(){return gd} var id=$c.extend({key:function(a){if(a.key){var b=cd[a.key]||a.key;if("Unidentified"!==b)return b}return"keypress"===a.type?(a=bd(a),13===a?"Enter":String.fromCharCode(a)):"keydown"===a.type||"keyup"===a.type?ed[a.keyCode]||"Unidentified":""},location:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,repeat:null,locale:null,getModifierState:hd,charCode:function(a){return"keypress"===a.type?bd(a):0},keyCode:function(a){return"keydown"===a.type||"keyup"===a.type?a.keyCode:0},which:function(a){return"keypress"=== a.type?bd(a):"keydown"===a.type||"keyup"===a.type?a.keyCode:0}}),jd=0,kd=0,ld=!1,md=!1,nd=$c.extend({screenX:null,screenY:null,clientX:null,clientY:null,pageX:null,pageY:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,getModifierState:hd,button:null,buttons:null,relatedTarget:function(a){return a.relatedTarget||(a.fromElement===a.srcElement?a.toElement:a.fromElement)},movementX:function(a){if("movementX"in a)return a.movementX;var b=jd;jd=a.screenX;return ld?"mousemove"===a.type?a.screenX- b:0:(ld=!0,0)},movementY:function(a){if("movementY"in a)return a.movementY;var b=kd;kd=a.screenY;return md?"mousemove"===a.type?a.screenY-b:0:(md=!0,0)}}),od=nd.extend({pointerId:null,width:null,height:null,pressure:null,tangentialPressure:null,tiltX:null,tiltY:null,twist:null,pointerType:null,isPrimary:null}),pd=nd.extend({dataTransfer:null}),qd=$c.extend({touches:null,targetTouches:null,changedTouches:null,altKey:null,metaKey:null,ctrlKey:null,shiftKey:null,getModifierState:hd}),rd=E.extend({propertyName:null, elapsedTime:null,pseudoElement:null}),sd=nd.extend({deltaX:function(a){return"deltaX"in a?a.deltaX:"wheelDeltaX"in a?-a.wheelDeltaX:0},deltaY:function(a){return"deltaY"in a?a.deltaY:"wheelDeltaY"in a?-a.wheelDeltaY:"wheelDelta"in a?-a.wheelDelta:0},deltaZ:null,deltaMode:null}),td=[["blur","blur",0],["cancel","cancel",0],["click","click",0],["close","close",0],["contextmenu","contextMenu",0],["copy","copy",0],["cut","cut",0],["auxclick","auxClick",0],["dblclick","doubleClick",0],["dragend","dragEnd", 0],["dragstart","dragStart",0],["drop","drop",0],["focus","focus",0],["input","input",0],["invalid","invalid",0],["keydown","keyDown",0],["keypress","keyPress",0],["keyup","keyUp",0],["mousedown","mouseDown",0],["mouseup","mouseUp",0],["paste","paste",0],["pause","pause",0],["play","play",0],["pointercancel","pointerCancel",0],["pointerdown","pointerDown",0],["pointerup","pointerUp",0],["ratechange","rateChange",0],["reset","reset",0],["seeked","seeked",0],["submit","submit",0],["touchcancel","touchCancel", 0],["touchend","touchEnd",0],["touchstart","touchStart",0],["volumechange","volumeChange",0],["drag","drag",1],["dragenter","dragEnter",1],["dragexit","dragExit",1],["dragleave","dragLeave",1],["dragover","dragOver",1],["mousemove","mouseMove",1],["mouseout","mouseOut",1],["mouseover","mouseOver",1],["pointermove","pointerMove",1],["pointerout","pointerOut",1],["pointerover","pointerOver",1],["scroll","scroll",1],["toggle","toggle",1],["touchmove","touchMove",1],["wheel","wheel",1],["abort","abort", 2],[Zb,"animationEnd",2],[$b,"animationIteration",2],[ac,"animationStart",2],["canplay","canPlay",2],["canplaythrough","canPlayThrough",2],["durationchange","durationChange",2],["emptied","emptied",2],["encrypted","encrypted",2],["ended","ended",2],["error","error",2],["gotpointercapture","gotPointerCapture",2],["load","load",2],["loadeddata","loadedData",2],["loadedmetadata","loadedMetadata",2],["loadstart","loadStart",2],["lostpointercapture","lostPointerCapture",2],["playing","playing",2],["progress", "progress",2],["seeking","seeking",2],["stalled","stalled",2],["suspend","suspend",2],["timeupdate","timeUpdate",2],[bc,"transitionEnd",2],["waiting","waiting",2]],ud={},vd={},xd=0;for(;xd=b)return{node:c,offset:b-a};a=d}a:{for(;c;){if(c.nextSibling){c=c.nextSibling;break a}c=c.parentNode}c=void 0}c=ce(c)}} function ee(a,b){return a&&b?a===b?!0:a&&3===a.nodeType?!1:b&&3===b.nodeType?ee(a,b.parentNode):"contains"in a?a.contains(b):a.compareDocumentPosition?!!(a.compareDocumentPosition(b)&16):!1:!1}function fe(){for(var a=window,b=be();b instanceof a.HTMLIFrameElement;){try{var c="string"===typeof b.contentWindow.location.href}catch(d){c=!1}if(c)a=b.contentWindow;else break;b=be(a.document)}return b} function ge(a){var b=a&&a.nodeName&&a.nodeName.toLowerCase();return b&&("input"===b&&("text"===a.type||"search"===a.type||"tel"===a.type||"url"===a.type||"password"===a.type)||"textarea"===b||"true"===a.contentEditable)}var he="$",ie="/$",je="$?",ke="$!",le=null,me=null;function ne(a,b){switch(a){case "button":case "input":case "select":case "textarea":return!!b.autoFocus}return!1} function oe(a,b){return"textarea"===a||"option"===a||"noscript"===a||"string"===typeof b.children||"number"===typeof b.children||"object"===typeof b.dangerouslySetInnerHTML&&null!==b.dangerouslySetInnerHTML&&null!=b.dangerouslySetInnerHTML.__html}var pe="function"===typeof setTimeout?setTimeout:void 0,qe="function"===typeof clearTimeout?clearTimeout:void 0;function re(a){for(;null!=a;a=a.nextSibling){var b=a.nodeType;if(1===b||3===b)break}return a} function se(a){a=a.previousSibling;for(var b=0;a;){if(8===a.nodeType){var c=a.data;if(c===he||c===ke||c===je){if(0===b)return a;b--}else c===ie&&b++}a=a.previousSibling}return null}var te=Math.random().toString(36).slice(2),ue="__reactInternalInstance$"+te,ve="__reactEventHandlers$"+te,we="__reactContainere$"+te; function Fc(a){var b=a[ue];if(b)return b;for(var c=a.parentNode;c;){if(b=c[we]||c[ue]){c=b.alternate;if(null!==b.child||null!==c&&null!==c.child)for(a=se(a);null!==a;){if(c=a[ue])return c;a=se(a)}return b}a=c;c=a.parentNode}return null}function Cc(a){a=a[ue]||a[we];return!a||5!==a.tag&&6!==a.tag&&13!==a.tag&&3!==a.tag?null:a}function xe(a){if(5===a.tag||6===a.tag)return a.stateNode;throw Error(u(33));}function ye(a){return a[ve]||null}var ze=null,Ae=null,Be=null; function Ce(){if(Be)return Be;var a,b=Ae,c=b.length,d,e="value"in ze?ze.value:ze.textContent,f=e.length;for(a=0;a=He),Ke=String.fromCharCode(32),Le={beforeInput:{phasedRegistrationNames:{bubbled:"onBeforeInput",captured:"onBeforeInputCapture"},dependencies:["compositionend","keypress","textInput","paste"]},compositionEnd:{phasedRegistrationNames:{bubbled:"onCompositionEnd",captured:"onCompositionEndCapture"},dependencies:"blur compositionend keydown keypress keyup mousedown".split(" ")},compositionStart:{phasedRegistrationNames:{bubbled:"onCompositionStart", captured:"onCompositionStartCapture"},dependencies:"blur compositionstart keydown keypress keyup mousedown".split(" ")},compositionUpdate:{phasedRegistrationNames:{bubbled:"onCompositionUpdate",captured:"onCompositionUpdateCapture"},dependencies:"blur compositionupdate keydown keypress keyup mousedown".split(" ")}},Me=!1; function Ne(a,b){switch(a){case "keyup":return-1!==Fe.indexOf(b.keyCode);case "keydown":return 229!==b.keyCode;case "keypress":case "mousedown":case "blur":return!0;default:return!1}}function Oe(a){a=a.detail;return"object"===typeof a&&"data"in a?a.data:null}var Pe=!1;function Qe(a,b){switch(a){case "compositionend":return Oe(b);case "keypress":if(32!==b.which)return null;Me=!0;return Ke;case "textInput":return a=b.data,a===Ke&&Me?null:a;default:return null}} function Re(a,b){if(Pe)return"compositionend"===a||!Ge&&Ne(a,b)?(a=Ce(),Be=Ae=ze=null,Pe=!1,a):null;switch(a){case "paste":return null;case "keypress":if(!(b.ctrlKey||b.altKey||b.metaKey)||b.ctrlKey&&b.altKey){if(b.char&&1=document.documentMode,sf={select:{phasedRegistrationNames:{bubbled:"onSelect",captured:"onSelectCapture"},dependencies:"blur contextmenu dragend focus keydown keyup mousedown mouseup selectionchange".split(" ")}},tf=null,uf=null,vf=null,wf=!1; function xf(a,b){var c=b.window===b?b.document:9===b.nodeType?b:b.ownerDocument;if(wf||null==tf||tf!==be(c))return null;c=tf;"selectionStart"in c&&ge(c)?c={start:c.selectionStart,end:c.selectionEnd}:(c=(c.ownerDocument&&c.ownerDocument.defaultView||window).getSelection(),c={anchorNode:c.anchorNode,anchorOffset:c.anchorOffset,focusNode:c.focusNode,focusOffset:c.focusOffset});return vf&&qf(vf,c)?null:(vf=c,a=E.getPooled(sf.select,uf,a,b),a.type="select",a.target=tf,Sc(a),a)} var yf={eventTypes:sf,extractEvents:function(a,b,c,d){var e=d.window===d?d.document:9===d.nodeType?d:d.ownerDocument,f;if(!(f=!e)){a:{e=xc(e);f=ja.onSelect;for(var g=0;gBf||(a.current=Af[Bf],Af[Bf]=null,Bf--)} function I(a,b){Bf++;Af[Bf]=a.current;a.current=b}var Cf={},J={current:Cf},K={current:!1},Df=Cf;function Ef(a,b){var c=a.type.contextTypes;if(!c)return Cf;var d=a.stateNode;if(d&&d.__reactInternalMemoizedUnmaskedChildContext===b)return d.__reactInternalMemoizedMaskedChildContext;var e={},f;for(f in c)e[f]=b[f];d&&(a=a.stateNode,a.__reactInternalMemoizedUnmaskedChildContext=b,a.__reactInternalMemoizedMaskedChildContext=e);return e}function L(a){a=a.childContextTypes;return null!==a&&void 0!==a} function Ff(a){G(K,a);G(J,a)}function Gf(a){G(K,a);G(J,a)}function Hf(a,b,c){if(J.current!==Cf)throw Error(u(168));I(J,b,a);I(K,c,a)}function If(a,b,c){var d=a.stateNode;a=b.childContextTypes;if("function"!==typeof d.getChildContext)return c;d=d.getChildContext();for(var e in d)if(!(e in a))throw Error(u(108,Wa(b)||"Unknown",e));return n({},c,{},d)}function Jf(a){var b=a.stateNode;b=b&&b.__reactInternalMemoizedMergedChildContext||Cf;Df=J.current;I(J,b,a);I(K,K.current,a);return!0} function Kf(a,b,c){var d=a.stateNode;if(!d)throw Error(u(169));c?(b=If(a,b,Df),d.__reactInternalMemoizedMergedChildContext=b,G(K,a),G(J,a),I(J,b,a)):G(K,a);I(K,c,a)} var Lf=q.unstable_runWithPriority,Mf=q.unstable_scheduleCallback,Nf=q.unstable_cancelCallback,Of=q.unstable_shouldYield,Pf=q.unstable_requestPaint,Qf=q.unstable_now,Rf=q.unstable_getCurrentPriorityLevel,Sf=q.unstable_ImmediatePriority,Tf=q.unstable_UserBlockingPriority,Uf=q.unstable_NormalPriority,Vf=q.unstable_LowPriority,Wf=q.unstable_IdlePriority,Xf={},Yf=void 0!==Pf?Pf:function(){},Zf=null,$f=null,ag=!1,bg=Qf(),cg=1E4>bg?Qf:function(){return Qf()-bg}; function dg(){switch(Rf()){case Sf:return 99;case Tf:return 98;case Uf:return 97;case Vf:return 96;case Wf:return 95;default:throw Error(u(332));}}function eg(a){switch(a){case 99:return Sf;case 98:return Tf;case 97:return Uf;case 96:return Vf;case 95:return Wf;default:throw Error(u(332));}}function fg(a,b){a=eg(a);return Lf(a,b)}function gg(a,b,c){a=eg(a);return Mf(a,b,c)}function hg(a){null===Zf?(Zf=[a],$f=Mf(Sf,ig)):Zf.push(a);return Xf}function jg(){if(null!==$f){var a=$f;$f=null;Nf(a)}ig()} function ig(){if(!ag&&null!==Zf){ag=!0;var a=0;try{var b=Zf;fg(99,function(){for(;a=b&&(wg=!0),a.firstContext=null)}function xg(a,b){if(qg!==a&&!1!==b&&0!==b){if("number"!==typeof b||1073741823===b)qg=a,b=1073741823;b={context:a,observedBits:b,next:null};if(null===pg){if(null===og)throw Error(u(308));pg=b;og.dependencies={expirationTime:0,firstContext:b,responders:null}}else pg=pg.next=b}return a._currentValue}var yg=!1; function zg(a){return{baseState:a,firstUpdate:null,lastUpdate:null,firstCapturedUpdate:null,lastCapturedUpdate:null,firstEffect:null,lastEffect:null,firstCapturedEffect:null,lastCapturedEffect:null}}function Ag(a){return{baseState:a.baseState,firstUpdate:a.firstUpdate,lastUpdate:a.lastUpdate,firstCapturedUpdate:null,lastCapturedUpdate:null,firstEffect:null,lastEffect:null,firstCapturedEffect:null,lastCapturedEffect:null}} function Bg(a,b){return{expirationTime:a,suspenseConfig:b,tag:0,payload:null,callback:null,next:null,nextEffect:null}}function Cg(a,b){null===a.lastUpdate?a.firstUpdate=a.lastUpdate=b:(a.lastUpdate.next=b,a.lastUpdate=b)} function Dg(a,b){var c=a.alternate;if(null===c){var d=a.updateQueue;var e=null;null===d&&(d=a.updateQueue=zg(a.memoizedState))}else d=a.updateQueue,e=c.updateQueue,null===d?null===e?(d=a.updateQueue=zg(a.memoizedState),e=c.updateQueue=zg(c.memoizedState)):d=a.updateQueue=Ag(e):null===e&&(e=c.updateQueue=Ag(d));null===e||d===e?Cg(d,b):null===d.lastUpdate||null===e.lastUpdate?(Cg(d,b),Cg(e,b)):(Cg(d,b),e.lastUpdate=b)} function Eg(a,b){var c=a.updateQueue;c=null===c?a.updateQueue=zg(a.memoizedState):Fg(a,c);null===c.lastCapturedUpdate?c.firstCapturedUpdate=c.lastCapturedUpdate=b:(c.lastCapturedUpdate.next=b,c.lastCapturedUpdate=b)}function Fg(a,b){var c=a.alternate;null!==c&&b===c.updateQueue&&(b=a.updateQueue=Ag(b));return b} function Gg(a,b,c,d,e,f){switch(c.tag){case 1:return a=c.payload,"function"===typeof a?a.call(f,d,e):a;case 3:a.effectTag=a.effectTag&-4097|64;case 0:a=c.payload;e="function"===typeof a?a.call(f,d,e):a;if(null===e||void 0===e)break;return n({},d,e);case 2:yg=!0}return d} function Hg(a,b,c,d,e){yg=!1;b=Fg(a,b);for(var f=b.baseState,g=null,h=0,k=b.firstUpdate,l=f;null!==k;){var m=k.expirationTime;mx?(A=r,r=null):A=r.sibling;var p=y(e,r,h[x],k);if(null===p){null===r&&(r=A);break}a&& r&&null===p.alternate&&b(e,r);g=f(p,g,x);null===m?l=p:m.sibling=p;m=p;r=A}if(x===h.length)return c(e,r),l;if(null===r){for(;xx?(A=r,r=null):A=r.sibling;var z=y(e,r,p.value,k);if(null===z){null===r&&(r=A);break}a&&r&&null===z.alternate&&b(e,r);g=f(z,g,x);null===m?l=z:m.sibling=z;m=z;r=A}if(p.done)return c(e,r),l;if(null===r){for(;!p.done;x++,p=h.next())p=C(e,p.value,k),null!==p&&(g=f(p,g,x),null===m?l=p:m.sibling=p,m=p);return l}for(r=d(e,r);!p.done;x++,p=h.next())p=H(r,e,x,p.value,k),null!==p&&(a&&null!== p.alternate&&r.delete(null===p.key?x:p.key),g=f(p,g,x),null===m?l=p:m.sibling=p,m=p);a&&r.forEach(function(a){return b(e,a)});return l}return function(a,d,f,h){var k="object"===typeof f&&null!==f&&f.type===Ia&&null===f.key;k&&(f=f.props.children);var l="object"===typeof f&&null!==f;if(l)switch(f.$$typeof){case Ga:a:{l=f.key;for(k=d;null!==k;){if(k.key===l)if(7===k.tag?f.type===Ia:k.elementType===f.type){c(a,k.sibling);d=e(k,f.type===Ia?f.props.children:f.props,h);d.ref=Yg(a,k,f);d.return=a;a=d;break a}else{c(a, k);break}else b(a,k);k=k.sibling}f.type===Ia?(d=eh(f.props.children,a.mode,h,f.key),d.return=a,a=d):(h=ch(f.type,f.key,f.props,null,a.mode,h),h.ref=Yg(a,d,f),h.return=a,a=h)}return g(a);case Ha:a:{for(k=f.key;null!==d;){if(d.key===k)if(4===d.tag&&d.stateNode.containerInfo===f.containerInfo&&d.stateNode.implementation===f.implementation){c(a,d.sibling);d=e(d,f.children||[],h);d.return=a;a=d;break a}else{c(a,d);break}else b(a,d);d=d.sibling}d=dh(f,a.mode,h);d.return=a;a=d}return g(a)}if("string"=== typeof f||"number"===typeof f)return f=""+f,null!==d&&6===d.tag?(c(a,d.sibling),d=e(d,f,h),d.return=a,a=d):(c(a,d),d=bh(f,a.mode,h),d.return=a,a=d),g(a);if(Xg(f))return z(a,d,f,h);if(Ua(f))return ta(a,d,f,h);l&&Zg(a,f);if("undefined"===typeof f&&!k)switch(a.tag){case 1:case 0:throw a=a.type,Error(u(152,a.displayName||a.name||"Component"));}return c(a,d)}}var fh=$g(!0),gh=$g(!1),hh={},ih={current:hh},jh={current:hh},kh={current:hh};function lh(a){if(a===hh)throw Error(u(174));return a} function mh(a,b){I(kh,b,a);I(jh,a,a);I(ih,hh,a);var c=b.nodeType;switch(c){case 9:case 11:b=(b=b.documentElement)?b.namespaceURI:Qb(null,"");break;default:c=8===c?b.parentNode:b,b=c.namespaceURI||null,c=c.tagName,b=Qb(b,c)}G(ih,a);I(ih,b,a)}function nh(a){G(ih,a);G(jh,a);G(kh,a)}function oh(a){lh(kh.current);var b=lh(ih.current);var c=Qb(b,a.type);b!==c&&(I(jh,a,a),I(ih,c,a))}function ph(a){jh.current===a&&(G(ih,a),G(jh,a))}var M={current:0}; function qh(a){for(var b=a;null!==b;){if(13===b.tag){var c=b.memoizedState;if(null!==c&&(c=c.dehydrated,null===c||c.data===je||c.data===ke))return b}else if(19===b.tag&&void 0!==b.memoizedProps.revealOrder){if(0!==(b.effectTag&64))return b}else if(null!==b.child){b.child.return=b;b=b.child;continue}if(b===a)break;for(;null===b.sibling;){if(null===b.return||b.return===a)return null;b=b.return}b.sibling.return=b.return;b=b.sibling}return null}function rh(a,b){return{responder:a,props:b}} var sh=Ea.ReactCurrentDispatcher,N=Ea.ReactCurrentBatchConfig,th=0,uh=null,O=null,vh=null,wh=null,P=null,xh=null,yh=0,zh=null,Ah=0,Bh=!1,Ch=null,Gh=0;function Q(){throw Error(u(321));}function Hh(a,b){if(null===b)return!1;for(var c=0;cyh&&(yh=m,Jg(yh))):(Ig(m,k.suspenseConfig),f=k.eagerReducer===a?k.eagerState:a(f,k.action));g=k;k=k.next}while(null!==k&&k!==d);l||(h=g,e=f);of(f,b.memoizedState)||(wg=!0);b.memoizedState=f;b.baseUpdate=h;b.baseState=e;c.lastRenderedState=f}return[b.memoizedState,c.dispatch]} function Rh(a){var b=Nh();"function"===typeof a&&(a=a());b.memoizedState=b.baseState=a;a=b.queue={last:null,dispatch:null,lastRenderedReducer:Ph,lastRenderedState:a};a=a.dispatch=Sh.bind(null,uh,a);return[b.memoizedState,a]}function Th(a){return Qh(Ph,a)}function Uh(a,b,c,d){a={tag:a,create:b,destroy:c,deps:d,next:null};null===zh?(zh={lastEffect:null},zh.lastEffect=a.next=a):(b=zh.lastEffect,null===b?zh.lastEffect=a.next=a:(c=b.next,b.next=a,a.next=c,zh.lastEffect=a));return a} function Vh(a,b,c,d){var e=Nh();Ah|=a;e.memoizedState=Uh(b,c,void 0,void 0===d?null:d)}function Wh(a,b,c,d){var e=Oh();d=void 0===d?null:d;var f=void 0;if(null!==O){var g=O.memoizedState;f=g.destroy;if(null!==d&&Hh(d,g.deps)){Uh(0,c,f,d);return}}Ah|=a;e.memoizedState=Uh(b,c,f,d)}function Xh(a,b){return Vh(516,192,a,b)}function Yh(a,b){return Wh(516,192,a,b)} function Zh(a,b){if("function"===typeof b)return a=a(),b(a),function(){b(null)};if(null!==b&&void 0!==b)return a=a(),b.current=a,function(){b.current=null}}function $h(){}function ai(a,b){Nh().memoizedState=[a,void 0===b?null:b];return a}function bi(a,b){var c=Oh();b=void 0===b?null:b;var d=c.memoizedState;if(null!==d&&null!==b&&Hh(b,d[1]))return d[0];c.memoizedState=[a,b];return a} function Sh(a,b,c){if(!(25>Gh))throw Error(u(301));var d=a.alternate;if(a===uh||null!==d&&d===uh)if(Bh=!0,a={expirationTime:th,suspenseConfig:null,action:c,eagerReducer:null,eagerState:null,next:null},null===Ch&&(Ch=new Map),c=Ch.get(b),void 0===c)Ch.set(b,a);else{for(b=c;null!==b.next;)b=b.next;b.next=a}else{var e=Pg(),f=Mg.suspense;e=Qg(e,a,f);f={expirationTime:e,suspenseConfig:f,action:c,eagerReducer:null,eagerState:null,next:null};var g=b.last;if(null===g)f.next=f;else{var h=g.next;null!==h&& (f.next=h);g.next=f}b.last=f;if(0===a.expirationTime&&(null===d||0===d.expirationTime)&&(d=b.lastRenderedReducer,null!==d))try{var k=b.lastRenderedState,l=d(k,c);f.eagerReducer=d;f.eagerState=l;if(of(l,k))return}catch(m){}finally{}Rg(a,e)}} var Lh={readContext:xg,useCallback:Q,useContext:Q,useEffect:Q,useImperativeHandle:Q,useLayoutEffect:Q,useMemo:Q,useReducer:Q,useRef:Q,useState:Q,useDebugValue:Q,useResponder:Q,useDeferredValue:Q,useTransition:Q},Jh={readContext:xg,useCallback:ai,useContext:xg,useEffect:Xh,useImperativeHandle:function(a,b,c){c=null!==c&&void 0!==c?c.concat([a]):null;return Vh(4,36,Zh.bind(null,b,a),c)},useLayoutEffect:function(a,b){return Vh(4,36,a,b)},useMemo:function(a,b){var c=Nh();b=void 0===b?null:b;a=a();c.memoizedState= [a,b];return a},useReducer:function(a,b,c){var d=Nh();b=void 0!==c?c(b):b;d.memoizedState=d.baseState=b;a=d.queue={last:null,dispatch:null,lastRenderedReducer:a,lastRenderedState:b};a=a.dispatch=Sh.bind(null,uh,a);return[d.memoizedState,a]},useRef:function(a){var b=Nh();a={current:a};return b.memoizedState=a},useState:Rh,useDebugValue:$h,useResponder:rh,useDeferredValue:function(a,b){var c=Rh(a),d=c[0],e=c[1];Xh(function(){q.unstable_next(function(){var c=N.suspense;N.suspense=void 0===b?null:b;try{e(a)}finally{N.suspense= c}})},[a,b]);return d},useTransition:function(a){var b=Rh(!1),c=b[0],d=b[1];return[ai(function(b){d(!0);q.unstable_next(function(){var c=N.suspense;N.suspense=void 0===a?null:a;try{d(!1),b()}finally{N.suspense=c}})},[a,c]),c]}},Kh={readContext:xg,useCallback:bi,useContext:xg,useEffect:Yh,useImperativeHandle:function(a,b,c){c=null!==c&&void 0!==c?c.concat([a]):null;return Wh(4,36,Zh.bind(null,b,a),c)},useLayoutEffect:function(a,b){return Wh(4,36,a,b)},useMemo:function(a,b){var c=Oh();b=void 0===b? null:b;var d=c.memoizedState;if(null!==d&&null!==b&&Hh(b,d[1]))return d[0];a=a();c.memoizedState=[a,b];return a},useReducer:Qh,useRef:function(){return Oh().memoizedState},useState:Th,useDebugValue:$h,useResponder:rh,useDeferredValue:function(a,b){var c=Th(a),d=c[0],e=c[1];Yh(function(){q.unstable_next(function(){var c=N.suspense;N.suspense=void 0===b?null:b;try{e(a)}finally{N.suspense=c}})},[a,b]);return d},useTransition:function(a){var b=Th(!1),c=b[0],d=b[1];return[bi(function(b){d(!0);q.unstable_next(function(){var c= N.suspense;N.suspense=void 0===a?null:a;try{d(!1),b()}finally{N.suspense=c}})},[a,c]),c]}},ci=null,di=null,ei=!1;function fi(a,b){var c=gi(5,null,null,0);c.elementType="DELETED";c.type="DELETED";c.stateNode=b;c.return=a;c.effectTag=8;null!==a.lastEffect?(a.lastEffect.nextEffect=c,a.lastEffect=c):a.firstEffect=a.lastEffect=c} function hi(a,b){switch(a.tag){case 5:var c=a.type;b=1!==b.nodeType||c.toLowerCase()!==b.nodeName.toLowerCase()?null:b;return null!==b?(a.stateNode=b,!0):!1;case 6:return b=""===a.pendingProps||3!==b.nodeType?null:b,null!==b?(a.stateNode=b,!0):!1;case 13:return!1;default:return!1}} function ii(a){if(ei){var b=di;if(b){var c=b;if(!hi(a,b)){b=re(c.nextSibling);if(!b||!hi(a,b)){a.effectTag=a.effectTag&-1025|2;ei=!1;ci=a;return}fi(ci,c)}ci=a;di=re(b.firstChild)}else a.effectTag=a.effectTag&-1025|2,ei=!1,ci=a}}function ji(a){for(a=a.return;null!==a&&5!==a.tag&&3!==a.tag&&13!==a.tag;)a=a.return;ci=a} function ki(a){if(a!==ci)return!1;if(!ei)return ji(a),ei=!0,!1;var b=a.type;if(5!==a.tag||"head"!==b&&"body"!==b&&!oe(b,a.memoizedProps))for(b=di;b;)fi(a,b),b=re(b.nextSibling);ji(a);if(13===a.tag){a=a.memoizedState;a=null!==a?a.dehydrated:null;if(!a)throw Error(u(317));a:{a=a.nextSibling;for(b=0;a;){if(8===a.nodeType){var c=a.data;if(c===ie){if(0===b){di=re(a.nextSibling);break a}b--}else c!==he&&c!==ke&&c!==je||b++}a=a.nextSibling}di=null}}else di=ci?re(a.stateNode.nextSibling):null;return!0} function li(){di=ci=null;ei=!1}var mi=Ea.ReactCurrentOwner,wg=!1;function R(a,b,c,d){b.child=null===a?gh(b,null,c,d):fh(b,a.child,c,d)}function ni(a,b,c,d,e){c=c.render;var f=b.ref;vg(b,e);d=Ih(a,b,c,d,f,e);if(null!==a&&!wg)return b.updateQueue=a.updateQueue,b.effectTag&=-517,a.expirationTime<=e&&(a.expirationTime=0),oi(a,b,e);b.effectTag|=1;R(a,b,d,e);return b.child} function pi(a,b,c,d,e,f){if(null===a){var g=c.type;if("function"===typeof g&&!qi(g)&&void 0===g.defaultProps&&null===c.compare&&void 0===c.defaultProps)return b.tag=15,b.type=g,ri(a,b,g,d,e,f);a=ch(c.type,null,d,null,b.mode,f);a.ref=b.ref;a.return=b;return b.child=a}g=a.child;if(eb)&&Gj.set(a,b)))}} function Kj(a,b){a.expirationTimea?b:a} function Z(a){if(0!==a.lastExpiredTime)a.callbackExpirationTime=1073741823,a.callbackPriority=99,a.callbackNode=hg(Lj.bind(null,a));else{var b=Oj(a),c=a.callbackNode;if(0===b)null!==c&&(a.callbackNode=null,a.callbackExpirationTime=0,a.callbackPriority=90);else{var d=Pg();1073741823===b?d=99:1===b||2===b?d=95:(d=10*(1073741821-b)-10*(1073741821-d),d=0>=d?99:250>=d?98:5250>=d?97:95);if(null!==c){var e=a.callbackPriority;if(a.callbackExpirationTime===b&&e>=d)return;c!==Xf&&Nf(c)}a.callbackExpirationTime= b;a.callbackPriority=d;b=1073741823===b?hg(Lj.bind(null,a)):gg(d,Qj.bind(null,a),{timeout:10*(1073741821-b)-cg()});a.callbackNode=b}}} function Qj(a,b){Jj=0;if(b)return b=Pg(),Rj(a,b),Z(a),null;var c=Oj(a);if(0!==c){b=a.callbackNode;if((T&(oj|pj))!==S)throw Error(u(327));Sj();a===U&&c===W||Tj(a,c);if(null!==V){var d=T;T|=oj;var e=Uj(a);do try{Vj();break}catch(h){Wj(a,h)}while(1);rg();T=d;lj.current=e;if(X===rj)throw b=wj,Tj(a,c),Mj(a,c),Z(a),b;if(null===V)switch(e=a.finishedWork=a.current.alternate,a.finishedExpirationTime=c,d=X,U=null,d){case qj:case rj:throw Error(u(345));case sj:Rj(a,2=c){a.lastPingedTime=c;Tj(a,c);break}}f=Oj(a);if(0!==f&&f!==c)break;if(0!==d&&d!==c){a.lastPingedTime=d;break}a.timeoutHandle=pe(Yj.bind(null,a),e);break}Yj(a);break;case uj:Mj(a,c);d=a.lastSuspendedTime;c===d&&(a.nextKnownPendingLevel=Xj(e));if(Bj&&(e=a.lastPingedTime,0===e||e>=c)){a.lastPingedTime=c;Tj(a,c);break}e=Oj(a);if(0!==e&&e!==c)break;if(0!==d&&d!==c){a.lastPingedTime= d;break}1073741823!==yj?d=10*(1073741821-yj)-cg():1073741823===xj?d=0:(d=10*(1073741821-xj)-5E3,e=cg(),c=10*(1073741821-c)-e,d=e-d,0>d&&(d=0),d=(120>d?120:480>d?480:1080>d?1080:1920>d?1920:3E3>d?3E3:4320>d?4320:1960*kj(d/1960))-d,c=d?d=0:(e=g.busyDelayMs|0,f=cg()-(10*(1073741821-f)-(g.timeoutMs|0||5E3)),d=f<=e?0:e+d-f);if(10 component higher in the tree to provide a loading indicator or placeholder to display."+Xa(e))}X!==vj&&(X=sj);f=Ni(f,e);k=d;do{switch(k.tag){case 3:g=f;k.effectTag|=4096;k.expirationTime=b;var x=fj(k,g,b);Eg(k,x);break a;case 1:g=f;var A=k.type,p=k.stateNode;if(0===(k.effectTag&64)&&("function"===typeof A.getDerivedStateFromError||null!==p&&"function"===typeof p.componentDidCatch&& (null===jj||!jj.has(p)))){k.effectTag|=4096;k.expirationTime=b;var t=ij(k,g,b);Eg(k,t);break a}}k=k.return}while(null!==k)}V=ek(V)}catch(v){b=v;continue}break}while(1)}function Uj(){var a=lj.current;lj.current=Lh;return null===a?Lh:a}function Ig(a,b){aAj&&(Aj=a)}function Zj(){for(;null!==V;)V=fk(V)}function Vj(){for(;null!==V&&!Of();)V=fk(V)} function fk(a){var b=gk(a.alternate,a,W);a.memoizedProps=a.pendingProps;null===b&&(b=ek(a));mj.current=null;return b} function ek(a){V=a;do{var b=V.alternate;a=V.return;if(0===(V.effectTag&2048)){a:{var c=b;b=V;var d=W;var e=b.pendingProps;switch(b.tag){case 2:break;case 16:break;case 15:case 0:break;case 1:L(b.type)&&Ff(b);break;case 3:nh(b);Gf(b);e=b.stateNode;e.pendingContext&&(e.context=e.pendingContext,e.pendingContext=null);(null===c||null===c.child)&&ki(b)&&Ci(b);Ii(b);break;case 5:ph(b);d=lh(kh.current);var f=b.type;if(null!==c&&null!=b.stateNode)Ji(c,b,f,e,d),c.ref!==b.ref&&(b.effectTag|=128);else if(e){var g= lh(ih.current);if(ki(b)){e=b;var h=e.stateNode;c=e.type;var k=e.memoizedProps,l=d;h[ue]=e;h[ve]=k;f=void 0;d=h;switch(c){case "iframe":case "object":case "embed":F("load",d);break;case "video":case "audio":for(h=0;h\x3c/script>",h=k.removeChild(k.firstChild)):"string"===typeof k.is?h=h.createElement(l,{is:k.is}):(h=h.createElement(l),"select"===l&&(l=h,k.multiple?l.multiple=!0:k.size&&(l.size=k.size))):h=h.createElementNS(g,l);k=h;k[ue]=c;k[ve]=e;Hi(k,b,!1,!1);b.stateNode=k;l=f;c=e;var m=d,C=Zd(l,c);switch(l){case "iframe":case "object":case "embed":F("load", k);d=c;break;case "video":case "audio":for(d=0;de.tailExpiration&&1f&&(f=c),k>f&&(f=k),d=d.sibling;e.childExpirationTime=f}if(null!==b)return b;null!==a&&0===(a.effectTag&2048)&&(null===a.firstEffect&&(a.firstEffect=V.firstEffect),null!==V.lastEffect&&(null!==a.lastEffect&&(a.lastEffect.nextEffect=V.firstEffect), a.lastEffect=V.lastEffect),1a?b:a}function Yj(a){var b=dg();fg(99,ik.bind(null,a,b));return null} function ik(a,b){Sj();if((T&(oj|pj))!==S)throw Error(u(327));var c=a.finishedWork,d=a.finishedExpirationTime;if(null===c)return null;a.finishedWork=null;a.finishedExpirationTime=0;if(c===a.current)throw Error(u(177));a.callbackNode=null;a.callbackExpirationTime=0;a.callbackPriority=90;a.nextKnownPendingLevel=0;var e=Xj(c);a.firstPendingTime=e;d<=a.lastSuspendedTime?a.firstSuspendedTime=a.lastSuspendedTime=a.nextKnownPendingLevel=0:d<=a.firstSuspendedTime&&(a.firstSuspendedTime=d-1);d<=a.lastPingedTime&& (a.lastPingedTime=0);d<=a.lastExpiredTime&&(a.lastExpiredTime=0);a===U&&(V=U=null,W=0);1h&&(l=h,h=g,g=l),l=de(p,g),m=de(p,h),l&&m&&(1!==v.rangeCount||v.anchorNode!==l.node||v.anchorOffset!==l.offset||v.focusNode!==m.node||v.focusOffset!==m.offset)&&(t=t.createRange(),t.setStart(l.node,l.offset),v.removeAllRanges(),g>h?(v.addRange(t),v.extend(m.node,m.offset)):(t.setEnd(m.node,m.offset),v.addRange(t))))));t=[];for(v=p;v=v.parentNode;)1===v.nodeType&&t.push({element:v,left:v.scrollLeft,top:v.scrollTop});"function"=== typeof p.focus&&p.focus();for(p=0;p=c)return yi(a,b,c);I(M,M.current& 1,b);b=oi(a,b,c);return null!==b?b.sibling:null}I(M,M.current&1,b);break;case 19:d=b.childExpirationTime>=c;if(0!==(a.effectTag&64)){if(d)return Bi(a,b,c);b.effectTag|=64}e=b.memoizedState;null!==e&&(e.rendering=null,e.tail=null);I(M,M.current,b);if(!d)return null}return oi(a,b,c)}wg=!1}}else wg=!1;b.expirationTime=0;switch(b.tag){case 2:d=b.type;null!==a&&(a.alternate=null,b.alternate=null,b.effectTag|=2);a=b.pendingProps;e=Ef(b,J.current);vg(b,c);e=Ih(null,b,d,a,e,c);b.effectTag|=1;if("object"=== typeof e&&null!==e&&"function"===typeof e.render&&void 0===e.$$typeof){b.tag=1;Mh();if(L(d)){var f=!0;Jf(b)}else f=!1;b.memoizedState=null!==e.state&&void 0!==e.state?e.state:null;var g=d.getDerivedStateFromProps;"function"===typeof g&&Og(b,d,g,a);e.updater=Sg;b.stateNode=e;e._reactInternalFiber=b;Wg(b,d,a,c);b=vi(null,b,d,!0,f,c)}else b.tag=0,R(null,b,e,c),b=b.child;return b;case 16:e=b.elementType;null!==a&&(a.alternate=null,b.alternate=null,b.effectTag|=2);a=b.pendingProps;Va(e);if(1!==e._status)throw e._result; e=e._result;b.type=e;f=b.tag=nk(e);a=mg(e,a);switch(f){case 0:b=si(null,b,e,a,c);break;case 1:b=ui(null,b,e,a,c);break;case 11:b=ni(null,b,e,a,c);break;case 14:b=pi(null,b,e,mg(e.type,a),d,c);break;default:throw Error(u(306,e,""));}return b;case 0:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:mg(d,e),si(a,b,d,e,c);case 1:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:mg(d,e),ui(a,b,d,e,c);case 3:wi(b);d=b.updateQueue;if(null===d)throw Error(u(282));e=b.memoizedState;e=null!==e?e.element: null;Hg(b,d,b.pendingProps,null,c);d=b.memoizedState.element;if(d===e)li(),b=oi(a,b,c);else{if(e=b.stateNode.hydrate)di=re(b.stateNode.containerInfo.firstChild),ci=b,e=ei=!0;if(e)for(c=gh(b,null,d,c),b.child=c;c;)c.effectTag=c.effectTag&-3|1024,c=c.sibling;else R(a,b,d,c),li();b=b.child}return b;case 5:return oh(b),null===a&&ii(b),d=b.type,e=b.pendingProps,f=null!==a?a.memoizedProps:null,g=e.children,oe(d,e)?g=null:null!==f&&oe(d,f)&&(b.effectTag|=16),ti(a,b),b.mode&4&&1!==c&&e.hidden?(b.expirationTime= b.childExpirationTime=1,b=null):(R(a,b,g,c),b=b.child),b;case 6:return null===a&&ii(b),null;case 13:return yi(a,b,c);case 4:return mh(b,b.stateNode.containerInfo),d=b.pendingProps,null===a?b.child=fh(b,null,d,c):R(a,b,d,c),b.child;case 11:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:mg(d,e),ni(a,b,d,e,c);case 7:return R(a,b,b.pendingProps,c),b.child;case 8:return R(a,b,b.pendingProps.children,c),b.child;case 12:return R(a,b,b.pendingProps.children,c),b.child;case 10:a:{d=b.type._context; e=b.pendingProps;g=b.memoizedProps;f=e.value;sg(b,f);if(null!==g){var h=g.value;f=of(h,f)?0:("function"===typeof d._calculateChangedBits?d._calculateChangedBits(h,f):1073741823)|0;if(0===f){if(g.children===e.children&&!K.current){b=oi(a,b,c);break a}}else for(h=b.child,null!==h&&(h.return=b);null!==h;){var k=h.dependencies;if(null!==k){g=h.child;for(var l=k.firstContext;null!==l;){if(l.context===d&&0!==(l.observedBits&f)){1===h.tag&&(l=Bg(c,null),l.tag=2,Dg(h,l));h.expirationTime=b&&a<=b}function Mj(a,b){var c=a.firstSuspendedTime,d=a.lastSuspendedTime;cb||0===c)a.lastSuspendedTime=b;b<=a.lastPingedTime&&(a.lastPingedTime=0);b<=a.lastExpiredTime&&(a.lastExpiredTime=0)} function Nj(a,b){b>a.firstPendingTime&&(a.firstPendingTime=b);var c=a.firstSuspendedTime;0!==c&&(b>=c?a.firstSuspendedTime=a.lastSuspendedTime=a.nextKnownPendingLevel=0:b>=a.lastSuspendedTime&&(a.lastSuspendedTime=b+1),b>a.nextKnownPendingLevel&&(a.nextKnownPendingLevel=b))}function Rj(a,b){var c=a.lastExpiredTime;if(0===c||c>b)a.lastExpiredTime=b} function rk(a,b,c,d){var e=b.current,f=Pg(),g=Mg.suspense;f=Qg(f,e,g);a:if(c){c=c._reactInternalFiber;b:{if(ec(c)!==c||1!==c.tag)throw Error(u(170));var h=c;do{switch(h.tag){case 3:h=h.stateNode.context;break b;case 1:if(L(h.type)){h=h.stateNode.__reactInternalMemoizedMergedChildContext;break b}}h=h.return}while(null!==h);throw Error(u(171));}if(1===c.tag){var k=c.type;if(L(k)){c=If(c,k,h);break a}}c=h}else c=Cf;null===b.context?b.context=c:b.pendingContext=c;b=Bg(f,g);b.payload={element:a};d=void 0=== d?null:d;null!==d&&(b.callback=d);Dg(e,b);Rg(e,f);return f}function sk(a){a=a.current;if(!a.child)return null;switch(a.child.tag){case 5:return a.child.stateNode;default:return a.child.stateNode}}function tk(a,b){a=a.memoizedState;null!==a&&null!==a.dehydrated&&a.retryTime=H};l=function(){};exports.unstable_forceFrameRate=function(a){0>a||125L(n,c))void 0!==r&&0>L(r,n)?(a[d]=r,a[v]=c,d=v):(a[d]=n,a[m]=c,d=m);else if(void 0!==r&&0>L(r,c))a[d]=r,a[v]=c,d=v;else break a}}return b}return null}function L(a,b){var c=a.sortIndex-b.sortIndex;return 0!==c?c:a.id-b.id}var O=[],P=[],Q=1,R=null,S=3,T=!1,U=!1,V=!1; function W(a){for(var b=M(P);null!==b;){if(null===b.callback)N(P);else if(b.startTime<=a)N(P),b.sortIndex=b.expirationTime,K(O,b);else break;b=M(P)}}function X(a){V=!1;W(a);if(!U)if(null!==M(O))U=!0,f(Y);else{var b=M(P);null!==b&&g(X,b.startTime-a)}} function Y(a,b){U=!1;V&&(V=!1,h());T=!0;var c=S;try{W(b);for(R=M(O);null!==R&&(!(R.expirationTime>b)||a&&!k());){var d=R.callback;if(null!==d){R.callback=null;S=R.priorityLevel;var e=d(R.expirationTime<=b);b=exports.unstable_now();"function"===typeof e?R.callback=e:R===M(O)&&N(O);W(b)}else N(O);R=M(O)}if(null!==R)var m=!0;else{var n=M(P);null!==n&&g(X,n.startTime-b);m=!1}return m}finally{R=null,S=c,T=!1}} function Z(a){switch(a){case 1:return-1;case 2:return 250;case 5:return 1073741823;case 4:return 1E4;default:return 5E3}}var aa=l;exports.unstable_ImmediatePriority=1;exports.unstable_UserBlockingPriority=2;exports.unstable_NormalPriority=3;exports.unstable_IdlePriority=5;exports.unstable_LowPriority=4;exports.unstable_runWithPriority=function(a,b){switch(a){case 1:case 2:case 3:case 4:case 5:break;default:a=3}var c=S;S=a;try{return b()}finally{S=c}}; exports.unstable_next=function(a){switch(S){case 1:case 2:case 3:var b=3;break;default:b=S}var c=S;S=b;try{return a()}finally{S=c}}; exports.unstable_scheduleCallback=function(a,b,c){var d=exports.unstable_now();if("object"===typeof c&&null!==c){var e=c.delay;e="number"===typeof e&&0d?(a.sortIndex=e,K(P,a),null===M(O)&&a===M(P)&&(V?h():V=!0,g(X,e-d))):(a.sortIndex=c,K(O,a),U||T||(U=!0,f(Y)));return a};exports.unstable_cancelCallback=function(a){a.callback=null}; exports.unstable_wrapCallback=function(a){var b=S;return function(){var c=S;S=b;try{return a.apply(this,arguments)}finally{S=c}}};exports.unstable_getCurrentPriorityLevel=function(){return S};exports.unstable_shouldYield=function(){var a=exports.unstable_now();W(a);var b=M(O);return b!==R&&null!==R&&null!==b&&null!==b.callback&&b.startTime<=a&&b.expirationTime result for the // current iteration. result.value = unwrapped; resolve(result); }, function(error) { // If a rejected Promise was yielded, throw the rejection back // into the async generator function so it can be handled there. return invoke("throw", error, resolve, reject); }); } } var previousPromise; function enqueue(method, arg) { function callInvokeWithMethodAndArg() { return new Promise(function(resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = // If enqueue has been called before, then we want to wait until // all previous Promises have been resolved before calling invoke, // so that results are always delivered in the correct order. If // enqueue has not been called before, then it is important to // call invoke immediately, without waiting on a callback to fire, // so that the async generator function has the opportunity to do // any necessary setup in a predictable way. This predictability // is why the Promise constructor synchronously invokes its // executor callback, and why async functions synchronously // execute code before the first await. Since we implement simple // async functions in terms of async generators, it is especially // important to get this right, even though it requires care. previousPromise ? previousPromise.then( callInvokeWithMethodAndArg, // Avoid propagating failures to Promises returned by later // invocations of the iterator. callInvokeWithMethodAndArg ) : callInvokeWithMethodAndArg(); } // Define the unified helper method that is used to implement .next, // .throw, and .return (see defineIteratorMethods). this._invoke = enqueue; } defineIteratorMethods(AsyncIterator.prototype); AsyncIterator.prototype[asyncIteratorSymbol] = function () { return this; }; exports.AsyncIterator = AsyncIterator; // Note that simple async functions are implemented on top of // AsyncIterator objects; they just return a Promise for the value of // the final result produced by the iterator. exports.async = function(innerFn, outerFn, self, tryLocsList) { var iter = new AsyncIterator( wrap(innerFn, outerFn, self, tryLocsList) ); return exports.isGeneratorFunction(outerFn) ? iter // If outerFn is a generator, return the full iterator. : iter.next().then(function(result) { return result.done ? result.value : iter.next(); }); }; function makeInvokeMethod(innerFn, self, context) { var state = GenStateSuspendedStart; return function invoke(method, arg) { if (state === GenStateExecuting) { throw new Error("Generator is already running"); } if (state === GenStateCompleted) { if (method === "throw") { throw arg; } // Be forgiving, per 25.3.3.3.3 of the spec: // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume return doneResult(); } context.method = method; context.arg = arg; while (true) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if (context.method === "next") { // Setting context._sent for legacy support of Babel's // function.sent implementation. context.sent = context._sent = context.arg; } else if (context.method === "throw") { if (state === GenStateSuspendedStart) { state = GenStateCompleted; throw context.arg; } context.dispatchException(context.arg); } else if (context.method === "return") { context.abrupt("return", context.arg); } state = GenStateExecuting; var record = tryCatch(innerFn, self, context); if (record.type === "normal") { // If an exception is thrown from innerFn, we leave state === // GenStateExecuting and loop back for another invocation. state = context.done ? GenStateCompleted : GenStateSuspendedYield; if (record.arg === ContinueSentinel) { continue; } return { value: record.arg, done: context.done }; } else if (record.type === "throw") { state = GenStateCompleted; // Dispatch the exception by looping back around to the // context.dispatchException(context.arg) call above. context.method = "throw"; context.arg = record.arg; } } }; } // Call delegate.iterator[context.method](context.arg) and handle the // result, either by returning a { value, done } result from the // delegate iterator, or by modifying context.method and context.arg, // setting context.delegate to null, and returning the ContinueSentinel. function maybeInvokeDelegate(delegate, context) { var method = delegate.iterator[context.method]; if (method === undefined) { // A .throw or .return when the delegate iterator has no .throw // method always terminates the yield* loop. context.delegate = null; if (context.method === "throw") { // Note: ["return"] must be used for ES3 parsing compatibility. if (delegate.iterator["return"]) { // If the delegate iterator has a return method, give it a // chance to clean up. context.method = "return"; context.arg = undefined; maybeInvokeDelegate(delegate, context); if (context.method === "throw") { // If maybeInvokeDelegate(context) changed context.method from // "return" to "throw", let that override the TypeError below. return ContinueSentinel; } } context.method = "throw"; context.arg = new TypeError( "The iterator does not provide a 'throw' method"); } return ContinueSentinel; } var record = tryCatch(method, delegate.iterator, context.arg); if (record.type === "throw") { context.method = "throw"; context.arg = record.arg; context.delegate = null; return ContinueSentinel; } var info = record.arg; if (! info) { context.method = "throw"; context.arg = new TypeError("iterator result is not an object"); context.delegate = null; return ContinueSentinel; } if (info.done) { // Assign the result of the finished delegate to the temporary // variable specified by delegate.resultName (see delegateYield). context[delegate.resultName] = info.value; // Resume execution at the desired location (see delegateYield). context.next = delegate.nextLoc; // If context.method was "throw" but the delegate handled the // exception, let the outer generator proceed normally. If // context.method was "next", forget context.arg since it has been // "consumed" by the delegate iterator. If context.method was // "return", allow the original .return call to continue in the // outer generator. if (context.method !== "return") { context.method = "next"; context.arg = undefined; } } else { // Re-yield the result returned by the delegate method. return info; } // The delegate iterator is finished, so forget it and continue with // the outer generator. context.delegate = null; return ContinueSentinel; } // Define Generator.prototype.{next,throw,return} in terms of the // unified ._invoke helper method. defineIteratorMethods(Gp); Gp[toStringTagSymbol] = "Generator"; // A Generator should always return itself as the iterator object when the // @@iterator function is called on it. Some browsers' implementations of the // iterator prototype chain incorrectly implement this, causing the Generator // object to not be returned from this call. This ensures that doesn't happen. // See https://github.com/facebook/regenerator/issues/274 for more details. Gp[iteratorSymbol] = function() { return this; }; Gp.toString = function() { return "[object Generator]"; }; function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; if (1 in locs) { entry.catchLoc = locs[1]; } if (2 in locs) { entry.finallyLoc = locs[2]; entry.afterLoc = locs[3]; } this.tryEntries.push(entry); } function resetTryEntry(entry) { var record = entry.completion || {}; record.type = "normal"; delete record.arg; entry.completion = record; } function Context(tryLocsList) { // The root entry object (effectively a try statement without a catch // or a finally block) gives us a place to store values thrown from // locations where there is no enclosing try statement. this.tryEntries = [{ tryLoc: "root" }]; tryLocsList.forEach(pushTryEntry, this); this.reset(true); } exports.keys = function(object) { var keys = []; for (var key in object) { keys.push(key); } keys.reverse(); // Rather than returning an object with a next method, we keep // things simple and return the next function itself. return function next() { while (keys.length) { var key = keys.pop(); if (key in object) { next.value = key; next.done = false; return next; } } // To avoid creating an additional object, we just hang the .value // and .done properties off the next function object itself. This // also ensures that the minifier will not anonymize the function. next.done = true; return next; }; }; function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) { return iteratorMethod.call(iterable); } if (typeof iterable.next === "function") { return iterable; } if (!isNaN(iterable.length)) { var i = -1, next = function next() { while (++i < iterable.length) { if (hasOwn.call(iterable, i)) { next.value = iterable[i]; next.done = false; return next; } } next.value = undefined; next.done = true; return next; }; return next.next = next; } } // Return an iterator with no values. return { next: doneResult }; } exports.values = values; function doneResult() { return { value: undefined, done: true }; } Context.prototype = { constructor: Context, reset: function(skipTempReset) { this.prev = 0; this.next = 0; // Resetting context._sent for legacy support of Babel's // function.sent implementation. this.sent = this._sent = undefined; this.done = false; this.delegate = null; this.method = "next"; this.arg = undefined; this.tryEntries.forEach(resetTryEntry); if (!skipTempReset) { for (var name in this) { // Not sure about the optimal order of these conditions: if (name.charAt(0) === "t" && hasOwn.call(this, name) && !isNaN(+name.slice(1))) { this[name] = undefined; } } } }, stop: function() { this.done = true; var rootEntry = this.tryEntries[0]; var rootRecord = rootEntry.completion; if (rootRecord.type === "throw") { throw rootRecord.arg; } return this.rval; }, dispatchException: function(exception) { if (this.done) { throw exception; } var context = this; function handle(loc, caught) { record.type = "throw"; record.arg = exception; context.next = loc; if (caught) { // If the dispatched exception was caught by a catch block, // then let that catch block handle the exception normally. context.method = "next"; context.arg = undefined; } return !! caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; var record = entry.completion; if (entry.tryLoc === "root") { // Exception thrown outside of any try block that could handle // it, so set the completion value of the entire function to // throw the exception. return handle("end"); } if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"); var hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) { return handle(entry.catchLoc, true); } else if (this.prev < entry.finallyLoc) { return handle(entry.finallyLoc); } } else if (hasCatch) { if (this.prev < entry.catchLoc) { return handle(entry.catchLoc, true); } } else if (hasFinally) { if (this.prev < entry.finallyLoc) { return handle(entry.finallyLoc); } } else { throw new Error("try statement without catch or finally"); } } } }, abrupt: function(type, arg) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { var finallyEntry = entry; break; } } if (finallyEntry && (type === "break" || type === "continue") && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc) { // Ignore the finally entry if control is not jumping to a // location outside the try/catch block. finallyEntry = null; } var record = finallyEntry ? finallyEntry.completion : {}; record.type = type; record.arg = arg; if (finallyEntry) { this.method = "next"; this.next = finallyEntry.finallyLoc; return ContinueSentinel; } return this.complete(record); }, complete: function(record, afterLoc) { if (record.type === "throw") { throw record.arg; } if (record.type === "break" || record.type === "continue") { this.next = record.arg; } else if (record.type === "return") { this.rval = this.arg = record.arg; this.method = "return"; this.next = "end"; } else if (record.type === "normal" && afterLoc) { this.next = afterLoc; } return ContinueSentinel; }, finish: function(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) { this.complete(entry.completion, entry.afterLoc); resetTryEntry(entry); return ContinueSentinel; } } }, "catch": function(tryLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc === tryLoc) { var record = entry.completion; if (record.type === "throw") { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } // The context.catch method must only be called with a location // argument that corresponds to a known catch block. throw new Error("illegal catch attempt"); }, delegateYield: function(iterable, resultName, nextLoc) { this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }; if (this.method === "next") { // Deliberately forget the last sent value so that we don't // accidentally pass it on to the delegate. this.arg = undefined; } return ContinueSentinel; } }; // Regardless of whether this script is executing as a CommonJS module // or not, return the runtime object so that we can declare the variable // regeneratorRuntime in the outer scope, which allows this module to be // injected easily by `bin/regenerator --include-runtime script.js`. return exports; }( // If this script is executing as a CommonJS module, use module.exports // as the regeneratorRuntime namespace. Otherwise create a new empty // object. Either way, the resulting object will be used to initialize // the regeneratorRuntime variable at the top of this file. true ? module.exports : undefined )); try { regeneratorRuntime = runtime; } catch (accidentalStrictMode) { // This module should not be running in strict mode, so the above // assignment should always work unless something is misconfigured. Just // in case runtime.js accidentally runs in strict mode, we can escape // strict mode using a global Function call. This could conceivably fail // if a Content Security Policy forbids using Function, but in that case // the proper solution is to fix the accidental strict mode problem. If // you've misconfigured your bundler to force strict mode and applied a // CSP to forbid Function, and you're not willing to fix either of those // problems, please detail your unique predicament in a GitHub issue. Function("r", "regeneratorRuntime = r")(runtime); } /***/ }), /* 89 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** @license React v16.12.0 * react-is.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ Object.defineProperty(exports,"__esModule",{value:!0}); var b="function"===typeof Symbol&&Symbol.for,c=b?Symbol.for("react.element"):60103,d=b?Symbol.for("react.portal"):60106,e=b?Symbol.for("react.fragment"):60107,f=b?Symbol.for("react.strict_mode"):60108,g=b?Symbol.for("react.profiler"):60114,h=b?Symbol.for("react.provider"):60109,k=b?Symbol.for("react.context"):60110,l=b?Symbol.for("react.async_mode"):60111,m=b?Symbol.for("react.concurrent_mode"):60111,n=b?Symbol.for("react.forward_ref"):60112,p=b?Symbol.for("react.suspense"):60113,q=b?Symbol.for("react.suspense_list"): 60120,r=b?Symbol.for("react.memo"):60115,t=b?Symbol.for("react.lazy"):60116,v=b?Symbol.for("react.fundamental"):60117,w=b?Symbol.for("react.responder"):60118,x=b?Symbol.for("react.scope"):60119;function y(a){if("object"===typeof a&&null!==a){var u=a.$$typeof;switch(u){case c:switch(a=a.type,a){case l:case m:case e:case g:case f:case p:return a;default:switch(a=a&&a.$$typeof,a){case k:case n:case t:case r:case h:return a;default:return u}}case d:return u}}}function z(a){return y(a)===m} exports.typeOf=y;exports.AsyncMode=l;exports.ConcurrentMode=m;exports.ContextConsumer=k;exports.ContextProvider=h;exports.Element=c;exports.ForwardRef=n;exports.Fragment=e;exports.Lazy=t;exports.Memo=r;exports.Portal=d;exports.Profiler=g;exports.StrictMode=f;exports.Suspense=p; exports.isValidElementType=function(a){return"string"===typeof a||"function"===typeof a||a===e||a===m||a===g||a===f||a===p||a===q||"object"===typeof a&&null!==a&&(a.$$typeof===t||a.$$typeof===r||a.$$typeof===h||a.$$typeof===k||a.$$typeof===n||a.$$typeof===v||a.$$typeof===w||a.$$typeof===x)};exports.isAsyncMode=function(a){return z(a)||y(a)===l};exports.isConcurrentMode=z;exports.isContextConsumer=function(a){return y(a)===k};exports.isContextProvider=function(a){return y(a)===h}; exports.isElement=function(a){return"object"===typeof a&&null!==a&&a.$$typeof===c};exports.isForwardRef=function(a){return y(a)===n};exports.isFragment=function(a){return y(a)===e};exports.isLazy=function(a){return y(a)===t};exports.isMemo=function(a){return y(a)===r};exports.isPortal=function(a){return y(a)===d};exports.isProfiler=function(a){return y(a)===g};exports.isStrictMode=function(a){return y(a)===f};exports.isSuspense=function(a){return y(a)===p}; /***/ }), /* 90 */ /***/ (function(module, exports, __webpack_require__) { /** * enigma.js v2.6.3 * Copyright (c) 2019 QlikTech International AB * This library is licensed under MIT - See the LICENSE file for full details */ (function (global, factory) { true ? module.exports = factory() : undefined; }(this, (function () { 'use strict'; /** * Utility functions */ var util = {}; util.isObject = function isObject(arg) { return typeof arg === 'object' && arg !== null; }; util.isNumber = function isNumber(arg) { return typeof arg === 'number'; }; util.isUndefined = function isUndefined(arg) { return arg === void 0; }; util.isFunction = function isFunction(arg){ return typeof arg === 'function'; }; /** * EventEmitter class */ function EventEmitter() { EventEmitter.init.call(this); } var nodeEventEmitter = EventEmitter; // Backwards-compat with node 0.10.x EventEmitter.EventEmitter = EventEmitter; EventEmitter.prototype._events = undefined; EventEmitter.prototype._maxListeners = undefined; // By default EventEmitters will print a warning if more than 10 listeners are // added to it. This is a useful default which helps finding memory leaks. EventEmitter.defaultMaxListeners = 10; EventEmitter.init = function() { this._events = this._events || {}; this._maxListeners = this._maxListeners || undefined; }; // Obviously not all Emitters should be limited to 10. This function allows // that to be increased. Set to zero for unlimited. EventEmitter.prototype.setMaxListeners = function(n) { if (!util.isNumber(n) || n < 0 || isNaN(n)) throw TypeError('n must be a positive number'); this._maxListeners = n; return this; }; EventEmitter.prototype.emit = function(type) { var er, handler, len, args, i, listeners; if (!this._events) this._events = {}; // If there is no 'error' event listener then throw. if (type === 'error' && !this._events.error) { er = arguments[1]; if (er instanceof Error) { throw er; // Unhandled 'error' event } else { throw Error('Uncaught, unspecified "error" event.'); } } handler = this._events[type]; if (util.isUndefined(handler)) return false; if (util.isFunction(handler)) { switch (arguments.length) { // fast cases case 1: handler.call(this); break; case 2: handler.call(this, arguments[1]); break; case 3: handler.call(this, arguments[1], arguments[2]); break; // slower default: len = arguments.length; args = new Array(len - 1); for (i = 1; i < len; i++) args[i - 1] = arguments[i]; handler.apply(this, args); } } else if (util.isObject(handler)) { len = arguments.length; args = new Array(len - 1); for (i = 1; i < len; i++) args[i - 1] = arguments[i]; listeners = handler.slice(); len = listeners.length; for (i = 0; i < len; i++) listeners[i].apply(this, args); } return true; }; EventEmitter.prototype.addListener = function(type, listener) { var m; if (!util.isFunction(listener)) throw TypeError('listener must be a function'); if (!this._events) this._events = {}; // To avoid recursion in the case that type === "newListener"! Before // adding it to the listeners, first emit "newListener". if (this._events.newListener) this.emit('newListener', type, util.isFunction(listener.listener) ? listener.listener : listener); if (!this._events[type]) // Optimize the case of one listener. Don't need the extra array object. this._events[type] = listener; else if (util.isObject(this._events[type])) // If we've already got an array, just append. this._events[type].push(listener); else // Adding the second element, need to change to array. this._events[type] = [this._events[type], listener]; // Check for listener leak if (util.isObject(this._events[type]) && !this._events[type].warned) { var m; if (!util.isUndefined(this._maxListeners)) { m = this._maxListeners; } else { m = EventEmitter.defaultMaxListeners; } if (m && m > 0 && this._events[type].length > m) { this._events[type].warned = true; if (util.isFunction(console.error)) { console.error('(node) warning: possible EventEmitter memory ' + 'leak detected. %d listeners added. ' + 'Use emitter.setMaxListeners() to increase limit.', this._events[type].length); } if (util.isFunction(console.trace)) console.trace(); } } return this; }; EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.once = function(type, listener) { if (!util.isFunction(listener)) throw TypeError('listener must be a function'); var fired = false; function g() { this.removeListener(type, g); if (!fired) { fired = true; listener.apply(this, arguments); } } g.listener = listener; this.on(type, g); return this; }; // emits a 'removeListener' event iff the listener was removed EventEmitter.prototype.removeListener = function(type, listener) { var list, position, length, i; if (!util.isFunction(listener)) throw TypeError('listener must be a function'); if (!this._events || !this._events[type]) return this; list = this._events[type]; length = list.length; position = -1; if (list === listener || (util.isFunction(list.listener) && list.listener === listener)) { delete this._events[type]; if (this._events.removeListener) this.emit('removeListener', type, listener); } else if (util.isObject(list)) { for (i = length; i-- > 0;) { if (list[i] === listener || (list[i].listener && list[i].listener === listener)) { position = i; break; } } if (position < 0) return this; if (list.length === 1) { list.length = 0; delete this._events[type]; } else { list.splice(position, 1); } if (this._events.removeListener) this.emit('removeListener', type, listener); } return this; }; EventEmitter.prototype.removeAllListeners = function(type) { var key, listeners; if (!this._events) return this; // not listening for removeListener, no need to emit if (!this._events.removeListener) { if (arguments.length === 0) this._events = {}; else if (this._events[type]) delete this._events[type]; return this; } // emit removeListener for all listeners on all events if (arguments.length === 0) { for (key in this._events) { if (key === 'removeListener') continue; this.removeAllListeners(key); } this.removeAllListeners('removeListener'); this._events = {}; return this; } listeners = this._events[type]; if (util.isFunction(listeners)) { this.removeListener(type, listeners); } else if (Array.isArray(listeners)) { // LIFO order while (listeners.length) this.removeListener(type, listeners[listeners.length - 1]); } delete this._events[type]; return this; }; EventEmitter.prototype.listeners = function(type) { var ret; if (!this._events || !this._events[type]) ret = []; else if (util.isFunction(this._events[type])) ret = [this._events[type]]; else ret = this._events[type].slice(); return ret; }; EventEmitter.listenerCount = function(emitter, type) { var ret; if (!emitter._events || !emitter._events[type]) ret = 0; else if (util.isFunction(emitter._events[type])) ret = 1; else ret = emitter._events[type].length; return ret; }; /** * @module EventEmitter * @private */ var Events = { /** * Function used to add event handling to objects passed in. * @param {Object} obj Object instance that will get event handling. */ mixin: function mixin(obj) { Object.keys(nodeEventEmitter.prototype).forEach(function (key) { obj[key] = nodeEventEmitter.prototype[key]; }); nodeEventEmitter.init(obj); } }; function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); } function isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _construct(Parent, args, Class) { if (isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); } function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } /** * Error containing a custom error code. * @extends Error * @property {number} code The error code as defined by `errorCodes` * @property {boolean} enigmaError=true */ var EnigmaError = /*#__PURE__*/ function (_Error) { _inherits(EnigmaError, _Error); function EnigmaError(name, code) { var _this; _classCallCheck(this, EnigmaError); _this = _possibleConstructorReturn(this, _getPrototypeOf(EnigmaError).call(this, name)); _this.code = code; _this.enigmaError = true; return _this; } return EnigmaError; }(_wrapNativeSuper(Error)); /** * Create an enigmaError * @param {Number} code A proper error code from `errorCodes` * @param {String} name A message/name of the enigmaError. * @returns {EnigmaError} */ function createEnigmaError(code, name) { return new EnigmaError(name, code); } /** * @enum */ var errorCodes = { /** * You're trying to send data on a socket that's not created * @type {number} */ NOT_CONNECTED: -1, /** * The object you're trying to fetch does not exist * @type {number} */ OBJECT_NOT_FOUND: -2, /** * Unexpected RPC response, expected array of patches * @type {number} */ EXPECTED_ARRAY_OF_PATCHES: -3, /** * Patchee is not an object we can patch * @type {number} */ PATCH_HAS_NO_PARENT: -4, /** * This entry is already defined with another key * @type {number} */ ENTRY_ALREADY_DEFINED: -5, /** * You need to supply a configuration * @type {number} */ NO_CONFIG_SUPPLIED: -6, /** * There's no promise object available (polyfill required?) * @type {number} */ PROMISE_REQUIRED: -7, /** * The schema struct type you requested does not exist * @type {number} */ SCHEMA_STRUCT_TYPE_NOT_FOUND: -8, /** * Can't override this function * @type {number} */ SCHEMA_MIXIN_CANT_OVERRIDE_FUNCTION: -9, /** * Extend is not allowed for this mixin * @type {number} */ SCHEMA_MIXIN_EXTEND_NOT_ALLOWED: -10, /** * Session suspended - no interaction allowed * @type {number} */ SESSION_SUSPENDED: -11, /** * onlyIfAttached supplied, but you got SESSION_CREATED * @type {number} */ SESSION_NOT_ATTACHED: -12 }; function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _classCallCheck$1(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } var RPC_CLOSE_NORMAL = 1000; var RPC_CLOSE_MANUAL_SUSPEND = 4000; var cacheId = 0; /** * The QIX Engine session object */ var Session = /*#__PURE__*/ function () { /** * Handle all JSON-RPC notification event, 'notification:*. Or handle a specific JSON-RPC * notification event, 'notification:OnConnected'. These events depend on the product you use QIX * Engine from. * @event Session#notification * @type {Object} */ /** * Handle websocket messages. Generally used in debugging purposes. traffic:* will handle all * websocket messages, traffic:sent will handle outgoing messages and traffic:received will handle * incoming messages. * @event Session#traffic * @type {Object} */ function Session(options) { _classCallCheck$1(this, Session); var session = this; Object.assign(session, options); this.Promise = this.config.Promise; this.definition = this.config.definition; Events.mixin(session); cacheId += 1; session.id = cacheId; session.rpc.on('socket-error', session.onRpcError.bind(session)); session.rpc.on('closed', session.onRpcClosed.bind(session)); session.rpc.on('message', session.onRpcMessage.bind(session)); session.rpc.on('notification', session.onRpcNotification.bind(session)); session.rpc.on('traffic', session.onRpcTraffic.bind(session)); session.on('closed', function () { return session.onSessionClosed(); }); } /** * Event handler for re-triggering error events from RPC. * @private * @emits socket-error * @param {Error} err Webocket error event. */ _createClass(Session, [{ key: "onRpcError", value: function onRpcError(err) { if (this.suspendResume.isSuspended) { return; } this.emit('socket-error', err); } /** * Event handler for the RPC close event. * @private * @emits Session#suspended * @emits Session#closed * @param {Event} evt WebSocket close event. */ }, { key: "onRpcClosed", value: function onRpcClosed(evt) { var _this = this; /** * Handle suspended state. This event is triggered in two cases (listed below). It is useful * in scenarios where you for example want to block interaction in your application until you * are resumed again. If config.suspendOnClose is true and there was a network disconnect * (socked closed) or if you ran session.suspend(). * @event Session#suspended * @type {Object} * @param {Object} evt Event object. * @param {String} evt.initiator String indication what triggered the suspended state. Possible * values network, manual. */ if (this.suspendResume.isSuspended) { return; } if (evt.code === RPC_CLOSE_NORMAL || evt.code === RPC_CLOSE_MANUAL_SUSPEND) { return; } if (this.config.suspendOnClose) { var code = evt.code, reason = evt.reason; this.suspendResume.suspend().then(function () { return _this.emit('suspended', { initiator: 'network', code: code, reason: reason }); }); } else { this.emit('closed', evt); } } /** * Event handler for the RPC message event. * @private * @param {Object} response JSONRPC response. */ }, { key: "onRpcMessage", value: function onRpcMessage(response) { var _this2 = this; if (this.suspendResume.isSuspended) { return; } if (response.change) { response.change.forEach(function (handle) { return _this2.emitHandleChanged(handle); }); } if (response.close) { response.close.forEach(function (handle) { return _this2.emitHandleClosed(handle); }); } } /** * Event handler for the RPC notification event. * @private * @emits Session#notification * @param {Object} response The JSONRPC notification. */ }, { key: "onRpcNotification", value: function onRpcNotification(response) { this.emit('notification:*', response.method, response.params); this.emit("notification:".concat(response.method), response.params); } /** * Event handler for the RPC traffic event. * @private * @emits Session#traffic * @param {String} dir The traffic direction, sent or received. * @param {Object} data JSONRPC request/response/WebSocket message. * @param {Number} handle The associated handle. */ }, { key: "onRpcTraffic", value: function onRpcTraffic(dir, data, handle) { this.emit('traffic:*', dir, data); this.emit("traffic:".concat(dir), data); var api = this.apis.getApi(handle); if (api) { api.emit('traffic:*', dir, data); api.emit("traffic:".concat(dir), data); } } /** * Event handler for cleaning up API instances when a session has been closed. * @private * @emits API#closed */ }, { key: "onSessionClosed", value: function onSessionClosed() { this.apis.getApis().forEach(function (entry) { entry.api.emit('closed'); entry.api.removeAllListeners(); }); this.apis.clear(); } /** * Function used to get an API for a backend object. * @private * @param {Object} args Arguments used to create object API. * @param {Number} args.handle Handle of the backend object. * @param {String} args.id ID of the backend object. * @param {String} args.type QIX type of the backend object. Can for example * be "Doc" or "GenericVariable". * @param {String} args.genericType Custom type of the backend object, if defined in qInfo. * @returns {*} Returns the generated and possibly augmented API. */ }, { key: "getObjectApi", value: function getObjectApi(args) { var handle = args.handle, id = args.id, type = args.type, genericType = args.genericType; var api = this.apis.getApi(handle); if (api) { return api; } var factory = this.definition.generate(type); api = factory(this, handle, id, genericType); this.apis.add(handle, api); return api; } /** * Establishes the websocket against the configured URL and returns the Global instance. * @emits Session#opened * @returns {Promise} Eventually resolved if the connection was successful. */ }, { key: "open", value: function open() { var _this3 = this; /** * Handle opened state. This event is triggered whenever the websocket is connected and ready for * communication. * @event Session#opened * @type {Object} */ if (!this.globalPromise) { var args = { handle: -1, id: 'Global', type: 'Global', genericType: 'Global' }; this.globalPromise = this.rpc.open().then(function () { return _this3.getObjectApi(args); }).then(function (global) { _this3.emit('opened'); return global; }); } return this.globalPromise; } /** * Function used to send data on the RPC socket. * @param {Object} request The request to be sent. (data and some meta info) * @returns {Object} Returns a promise instance. */ }, { key: "send", value: function send(request) { var _this4 = this; if (this.suspendResume.isSuspended) { return this.Promise.reject(createEnigmaError(errorCodes.SESSION_SUSPENDED, 'Session suspended')); } request.id = this.rpc.createRequestId(); var promise = this.intercept.executeRequests(this, this.Promise.resolve(request)).then(function (augmentedRequest) { var data = _objectSpread({}, _this4.config.protocol, {}, augmentedRequest); // the outKey value is used by multiple-out interceptor, at some point // we need to refactor that implementation and figure out how to transport // this value without hijacking the JSONRPC request object: delete data.outKey; var response = _this4.rpc.send(data); augmentedRequest.retry = function () { return _this4.send(request); }; return _this4.intercept.executeResponses(_this4, response, augmentedRequest); }); Session.addToPromiseChain(promise, 'requestId', request.id); return promise; } /** * Suspends the enigma.js session by closing the websocket and rejecting all method calls * until is has been resumed again. * @emits Session#suspended * @param {Number} [code=4000] - The reason code for suspending the connection. * @param {String} [reason=""] - The human readable string describing * why the connection is suspended. * @returns {Promise} Eventually resolved when the websocket has been closed. */ }, { key: "suspend", value: function suspend() { var _this5 = this; var code = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 4000; var reason = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ''; return this.suspendResume.suspend(code, reason).then(function () { return _this5.emit('suspended', { initiator: 'manual', code: code, reason: reason }); }); } /** * Resumes a previously suspended enigma.js session by re-creating the websocket and, * if possible, re-open the document as well as refreshing the internal cashes. If successful, * changed events will be triggered on all generated APIs, and on the ones it was unable to * restore, the closed event will be triggered. * @emits Session#resumed * @param {Boolean} onlyIfAttached If true, resume only if the session was re-attached properly. * @returns {Promise} Eventually resolved when the websocket (and potentially the * previously opened document, and generated APIs) has been restored, rejected when it fails any * of those steps, or when onlyIfAttached is true and a new session was created. */ }, { key: "resume", value: function resume(onlyIfAttached) { var _this6 = this; /** * Handle resumed state. This event is triggered when the session was properly resumed. It is * useful in scenarios where you for example can close blocking modal dialogs and allow the user * to interact with your application again. * @event Session#resumed * @type {Object} */ return this.suspendResume.resume(onlyIfAttached).then(function (value) { _this6.emit('resumed'); return value; }); } /** * Closes the websocket and cleans up internal caches, also triggers the closed event * on all generated APIs. Note that you have to manually invoke this when you want to * close a session and config.suspendOnClose is true. * @emits Session#closed * @param {Number} [code=1000] - The reason code for closing the connection. * @param {String} [reason=""] - The human readable string describing why the connection is closed. * @returns {Promise} Eventually resolved when the websocket has been closed. */ }, { key: "close", value: function close() { var _this7 = this; var code = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1000; var reason = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ''; /** * Handle closed state. This event is triggered when the underlying websocket is closed and * config.suspendOnClose is false. * @event Session#closed * @type {Object} */ this.globalPromise = undefined; return this.rpc.close(code, reason).then(function (evt) { return _this7.emit('closed', evt); }); } /** * Given a handle, this function will emit the 'changed' event on the * corresponding API instance. * @private * @param {Number} handle The handle of the API instance. * @emits API#changed */ }, { key: "emitHandleChanged", value: function emitHandleChanged(handle) { var api = this.apis.getApi(handle); if (api) { api.emit('changed'); } } /** * Given a handle, this function will emit the 'closed' event on the * corresponding API instance. * @private * @param {Number} handle The handle of the API instance. * @emits API#closed */ }, { key: "emitHandleClosed", value: function emitHandleClosed(handle) { var api = this.apis.getApi(handle); if (api) { api.emit('closed'); api.removeAllListeners(); } } /** * Function used to add info on the promise chain. * @private * @param {Promise} promise The promise to add info on. * @param {String} name The property to add info on. * @param {Any} value The info to add. */ }], [{ key: "addToPromiseChain", value: function addToPromiseChain(promise, name, value) { promise[name] = value; var then = promise.then; promise.then = function patchedThen() { for (var _len = arguments.length, params = new Array(_len), _key = 0; _key < _len; _key++) { params[_key] = arguments[_key]; } var chain = then.apply(this, params); Session.addToPromiseChain(chain, name, value); return chain; }; } }]); return Session; }(); function _classCallCheck$2(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties$1(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass$1(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties$1(Constructor.prototype, protoProps); if (staticProps) _defineProperties$1(Constructor, staticProps); return Constructor; } /** * Key-value cache * @private */ var KeyValueCache = /*#__PURE__*/ function () { function KeyValueCache() { _classCallCheck$2(this, KeyValueCache); this.entries = {}; } /** * Adds an entry. * @private * @function KeyValueCache#add * @param {String} key The key representing an entry. * @param {*} entry The entry to be added. */ _createClass$1(KeyValueCache, [{ key: "add", value: function add(key, entry) { key += ''; if (typeof this.entries[key] !== 'undefined') { throw createEnigmaError(errorCodes.ENTRY_ALREADY_DEFINED, "Entry already defined with key ".concat(key)); } this.entries[key] = entry; } /** * Sets an entry. * @private * @function KeyValueCache#set * @param {String} key The key representing an entry. * @param {*} entry The entry. */ }, { key: "set", value: function set(key, entry) { key += ''; this.entries[key] = entry; } /** * Removes an entry. * @private * @function KeyValueCache#remove * @param {String} key The key representing an entry. */ }, { key: "remove", value: function remove(key) { delete this.entries[key]; } /** * Gets an entry. * @private * @function KeyValueCache#get * @param {String} key The key representing an entry. * @returns {*} The entry for the key. */ }, { key: "get", value: function get(key) { return this.entries[key]; } /** * Gets a list of all entries. * @private * @function KeyValueCache#getAll * @returns {Array} The list of entries including its `key` and `value` properties. */ }, { key: "getAll", value: function getAll() { var _this = this; return Object.keys(this.entries).map(function (key) { return { key: key, value: _this.entries[key] }; }); } /** * Gets a key for an entry. * @private * @function KeyValueCache#getKey * @param {*} entry The entry to locate the key for. * @returns {String} The key representing an entry. */ }, { key: "getKey", value: function getKey(entry) { var _this2 = this; return Object.keys(this.entries).filter(function (key) { return _this2.entries[key] === entry; })[0]; } /** * Clears the cache of all entries. * @private * @function KeyValueCache#clear */ }, { key: "clear", value: function clear() { this.entries = {}; } }]); return KeyValueCache; }(); function _classCallCheck$3(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties$2(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass$2(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties$2(Constructor.prototype, protoProps); if (staticProps) _defineProperties$2(Constructor, staticProps); return Constructor; } function _typeof$1(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof$1 = function _typeof(obj) { return typeof obj; }; } else { _typeof$1 = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof$1(obj); } var hasOwnProperty$1 = Object.prototype.hasOwnProperty; /** * Returns the camelCase counterpart of a symbol. * @private * @param {String} symbol The symbol. * @return the camelCase counterpart. */ function toCamelCase(symbol) { return symbol.substring(0, 1).toLowerCase() + symbol.substring(1); } /** * A facade function that allows parameters to be passed either by name * (through an object), or by position (through an array). * @private * @param {Function} base The function that is being overriden. Will be * called with parameters in array-form. * @param {Object} defaults Parameter list and it's default values. * @param {*} params The parameters. */ function namedParamFacade(base, defaults) { for (var _len = arguments.length, params = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { params[_key - 2] = arguments[_key]; } if (params.length === 1 && _typeof$1(params[0]) === 'object' && !Array.isArray(params[0])) { var valid = Object.keys(params[0]).every(function (key) { return hasOwnProperty$1.call(defaults, key); }); if (valid) { params = Object.keys(defaults).map(function (key) { return params[0][key] || defaults[key]; }); } } return base.apply(this, params); } /** * Qix schema definition. * @private */ var Schema = /*#__PURE__*/ function () { /** * Create a new schema instance. * @private * @param {Configuration} config The configuration for QIX. */ function Schema(config) { _classCallCheck$3(this, Schema); this.config = config; this.Promise = config.Promise; this.schema = config.schema; this.mixins = new KeyValueCache(); this.types = new KeyValueCache(); } _createClass$2(Schema, [{ key: "registerMixin", value: function registerMixin(_ref) { var _this = this; var types = _ref.types, type = _ref.type, extend = _ref.extend, override = _ref.override, init = _ref.init; if (!Array.isArray(types)) { types = [types]; } // to support a single type if (type) { types.push(type); } var cached = { extend: extend, override: override, init: init }; types.forEach(function (typeKey) { var entryList = _this.mixins.get(typeKey); if (entryList) { entryList.push(cached); } else { _this.mixins.add(typeKey, [cached]); } }); } /** * Function used to generate a type definition. * @private * @param {String} type The type. * @returns {{create: Function, def: Object}} Returns an object with a definition * of the type and a create factory. */ }, { key: "generate", value: function generate(type) { var entry = this.types.get(type); if (entry) { return entry; } if (!this.schema.structs[type]) { throw createEnigmaError(errorCodes.SCHEMA_STRUCT_TYPE_NOT_FOUND, "".concat(type, " not found")); } var factory = this.generateApi(type, this.schema.structs[type]); this.types.add(type, factory); return factory; } /** * Function used to generate an API definition for a given type. * @private * @param {String} type The type to generate. * @param {Object} schema The schema describing the type. * @returns {{create: (function(session:Object, handle:Number, id:String, * customKey:String)), def: Object}} Returns the API definition. */ }, { key: "generateApi", value: function generateApi(type, schema) { var api = Object.create({}); this.generateDefaultApi(api, schema); // Generate default this.mixinType(type, api); // Mixin default type this.mixinNamedParamFacade(api, schema); // Mixin named parameter support return function create(session, handle, id, customKey) { var _this2 = this; var instance = Object.create(api); Events.mixin(instance); // Always mixin event-emitter per instance Object.defineProperties(instance, { session: { enumerable: true, value: session }, handle: { enumerable: true, value: handle, writable: true }, id: { enumerable: true, value: id }, type: { enumerable: true, value: type }, genericType: { enumerable: true, value: customKey } }); var mixinList = this.mixins.get(type) || []; if (customKey !== type) { this.mixinType(customKey, instance); // Mixin custom types mixinList = mixinList.concat(this.mixins.get(customKey) || []); } mixinList.forEach(function (mixin) { if (typeof mixin.init === 'function') { mixin.init({ config: _this2.config, api: instance }); } }); return instance; }.bind(this); } /** * Function used to generate the methods with the right handlers to the object * API that is being generated. * @private * @param {Object} api The object API that is currently being generated. * @param {Object} schema The API definition. */ }, { key: "generateDefaultApi", value: function generateDefaultApi(api, schema) { Object.keys(schema).forEach(function (method) { var out = schema[method].Out; var outKey = out.length === 1 ? out[0].Name : -1; var fnName = toCamelCase(method); api[fnName] = function generatedMethod() { for (var _len2 = arguments.length, params = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { params[_key2] = arguments[_key2]; } return this.session.send({ handle: this.handle, method: method, params: params, outKey: outKey }); }; }); } /** * Function used to add mixin methods to a specified API. * @private * @param {String} type Used to specify which mixin should be woven in. * @param {Object} api The object that will be woven. */ }, { key: "mixinType", value: function mixinType(type, api) { var mixinList = this.mixins.get(type); if (mixinList) { mixinList.forEach(function (_ref2) { var _ref2$extend = _ref2.extend, extend = _ref2$extend === void 0 ? {} : _ref2$extend, _ref2$override = _ref2.override, override = _ref2$override === void 0 ? {} : _ref2$override; Object.keys(override).forEach(function (key) { if (typeof api[key] === 'function' && typeof override[key] === 'function') { var baseFn = api[key]; api[key] = function wrappedFn() { for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { args[_key3] = arguments[_key3]; } return override[key].apply(this, [baseFn.bind(this)].concat(args)); }; } else { throw createEnigmaError(errorCodes.SCHEMA_MIXIN_CANT_OVERRIDE_FUNCTION, "No function to override. Type: ".concat(type, " function: ").concat(key)); } }); Object.keys(extend).forEach(function (key) { // handle overrides if (typeof api[key] === 'function' && typeof extend[key] === 'function') { throw createEnigmaError(errorCodes.SCHEMA_MIXIN_EXTEND_NOT_ALLOWED, "Extend is not allowed for this mixin. Type: ".concat(type, " function: ").concat(key)); } else { api[key] = extend[key]; } }); }); } } /** * Function used to mixin the named parameter facade. * @private * @param {Object} api The object API that is currently being generated. * @param {Object} schema The API definition. */ }, { key: "mixinNamedParamFacade", value: function mixinNamedParamFacade(api, schema) { Object.keys(schema).forEach(function (key) { var fnName = toCamelCase(key); var base = api[fnName]; var defaults = schema[key].In.reduce(function (result, item) { result[item.Name] = item.DefaultValue; return result; }, {}); api[fnName] = function namedParamWrapper() { for (var _len4 = arguments.length, params = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { params[_key4] = arguments[_key4]; } return namedParamFacade.apply(this, [base, defaults].concat(params)); }; }); } }]); return Schema; }(); function _classCallCheck$4(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties$3(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass$3(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties$3(Constructor.prototype, protoProps); if (staticProps) _defineProperties$3(Constructor, staticProps); return Constructor; } /** * Helper class for handling RPC calls * @private */ var RPCResolver = /*#__PURE__*/ function () { function RPCResolver(id, handle, resolve, reject) { _classCallCheck$4(this, RPCResolver); Events.mixin(this); this.id = id; this.handle = handle; this.resolve = resolve; this.reject = reject; } _createClass$3(RPCResolver, [{ key: "resolveWith", value: function resolveWith(data) { this.resolve(data); this.emit('resolved', this.id); } }, { key: "rejectWith", value: function rejectWith(err) { this.reject(err); this.emit('rejected', this.id); } }]); return RPCResolver; }(); function _classCallCheck$5(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties$4(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass$4(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties$4(Constructor.prototype, protoProps); if (staticProps) _defineProperties$4(Constructor, staticProps); return Constructor; } /** * This class handles remote procedure calls on a web socket. * @private */ var RPC = /*#__PURE__*/ function () { /** * Create a new RPC instance. * @private * @param {Object} options The configuration options for this class. * @param {Function} options.Promise The promise constructor to use. * @param {String} options.url The complete websocket URL used to connect. * @param {Function} options.createSocket The function callback to create a WebSocket. */ function RPC(options) { _classCallCheck$5(this, RPC); Object.assign(this, options); Events.mixin(this); this.resolvers = {}; this.requestId = 0; this.openedPromise = undefined; } /** * Opens a connection to the configured endpoint. * @private * @param {Boolean} force - ignores all previous and outstanding open calls if set to true. * @returns {Object} A promise instance. */ _createClass$4(RPC, [{ key: "open", value: function open() { var _this = this; var force = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; if (!force && this.openedPromise) { return this.openedPromise; } try { this.socket = this.createSocket(this.url); } catch (err) { return this.Promise.reject(err); } this.socket.onopen = this.onOpen.bind(this); this.socket.onclose = this.onClose.bind(this); this.socket.onerror = this.onError.bind(this); this.socket.onmessage = this.onMessage.bind(this); this.openedPromise = new this.Promise(function (resolve, reject) { return _this.registerResolver('opened', null, resolve, reject); }); this.closedPromise = new this.Promise(function (resolve, reject) { return _this.registerResolver('closed', null, resolve, reject); }); return this.openedPromise; } /** * Resolves the open promise when a connection is successfully established. * @private */ }, { key: "onOpen", value: function onOpen() { var _this2 = this; this.resolvers.opened.resolveWith(function () { return _this2.closedPromise; }); } /** * Resolves the close promise when a connection is closed. * @private * @param {Object} event - The event describing close. */ }, { key: "onClose", value: function onClose(event) { this.emit('closed', event); if (this.resolvers && this.resolvers.closed) { this.resolvers.closed.resolveWith(event); } this.rejectAllOutstandingResolvers({ code: -1, message: 'Socket closed' }); } /** * Closes a connection. * @private * @param {Number} [code=1000] - The reason code for closing the connection. * @param {String} [reason=""] - The human readable string describing why the connection is closed. * @returns {Object} Returns a promise instance. */ }, { key: "close", value: function close() { var code = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1000; var reason = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ''; if (this.socket) { this.socket.close(code, reason); this.socket = null; } return this.closedPromise; } /** * Emits an error event and rejects the open promise if an error is raised on the connection. * @private * @param {Object} event - The event describing the error. */ }, { key: "onError", value: function onError(event) { if (this.resolvers.opened) { this.resolvers.opened.rejectWith(event); } else { // only emit errors after the initial open promise has been resolved, // this makes it possible to catch early websocket errors as well // as run-time ones: this.emit('socket-error', event); } this.rejectAllOutstandingResolvers({ code: -1, message: 'Socket error' }); } /** * Parses the onMessage event on the connection and resolve the promise for the request. * @private * @param {Object} event - The event describing the message. */ }, { key: "onMessage", value: function onMessage(event) { var data = JSON.parse(event.data); var resolver = this.resolvers[data.id] || {}; this.emit('traffic', 'received', data, resolver.handle); if (typeof data.id !== 'undefined') { this.emit('message', data); this.resolvers[data.id].resolveWith(data); } else { this.emit(data.params ? 'notification' : 'message', data); } } /** * Rejects all outstanding resolvers. * @private * @param {Object} reason - The reject reason. */ }, { key: "rejectAllOutstandingResolvers", value: function rejectAllOutstandingResolvers(reason) { var _this3 = this; Object.keys(this.resolvers).forEach(function (id) { if (id === 'opened' || id === 'closed') { return; // "opened" and "closed" should not be handled here } var resolver = _this3.resolvers[id]; resolver.rejectWith(reason); }); } /** * Unregisters a resolver. * @private * @param {Number|String} id - The ID to unregister the resolver with. */ }, { key: "unregisterResolver", value: function unregisterResolver(id) { var resolver = this.resolvers[id]; resolver.removeAllListeners(); delete this.resolvers[id]; } /** * Registers a resolver. * @private * @param {Number|String} id - The ID to register the resolver with. * @param {Number} handle - The associated handle. * @returns {Function} The promise executor function. */ }, { key: "registerResolver", value: function registerResolver(id, handle, resolve, reject) { var _this4 = this; var resolver = new RPCResolver(id, handle, resolve, reject); this.resolvers[id] = resolver; resolver.on('resolved', function (resolvedId) { return _this4.unregisterResolver(resolvedId); }); resolver.on('rejected', function (rejectedId) { return _this4.unregisterResolver(rejectedId); }); } /** * Sends data on the socket. * @private * @param {Object} data - The data to send. * @returns {Object} A promise instance. */ }, { key: "send", value: function send(data) { var _this5 = this; if (!this.socket || this.socket.readyState !== this.socket.OPEN) { var error = createEnigmaError(errorCodes.NOT_CONNECTED, 'Not connected'); return this.Promise.reject(error); } if (!data.id) { data.id = this.createRequestId(); } data.jsonrpc = '2.0'; return new this.Promise(function (resolve, reject) { _this5.socket.send(JSON.stringify(data)); _this5.emit('traffic', 'sent', data, data.handle); return _this5.registerResolver(data.id, data.handle, resolve, reject); }); } }, { key: "createRequestId", value: function createRequestId() { this.requestId += 1; return this.requestId; } }]); return RPC; }(); function _classCallCheck$6(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties$5(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass$5(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties$5(Constructor.prototype, protoProps); if (staticProps) _defineProperties$5(Constructor, staticProps); return Constructor; } var ON_ATTACHED_TIMEOUT_MS = 5000; var RPC_CLOSE_MANUAL_SUSPEND$1 = 4000; var SuspendResume = /*#__PURE__*/ function () { /** * Creates a new SuspendResume instance. * @private * @param {Object} options The configuration option for this class. * @param {Promise} options.Promise The promise constructor to use. * @param {RPC} options.rpc The RPC instance to use when communicating towards Engine. * @param {ApiCache} options.apis The ApiCache instance to use. */ function SuspendResume(options) { var _this = this; _classCallCheck$6(this, SuspendResume); Object.assign(this, options); this.isSuspended = false; this.rpc.on('traffic', function (dir, data) { if (dir === 'sent' && data.method === 'OpenDoc') { _this.openDocParams = data.params; } }); } /** * Function used to restore the rpc connection. * @private * @param {Boolean} onlyIfAttached - if true, the returned promise will resolve * only if the session can be re-attached. * @returns {Object} Returns a promise instance. */ _createClass$5(SuspendResume, [{ key: "restoreRpcConnection", value: function restoreRpcConnection(onlyIfAttached) { var _this2 = this; return this.reopen(ON_ATTACHED_TIMEOUT_MS).then(function (sessionState) { if (sessionState === 'SESSION_CREATED' && onlyIfAttached) { return _this2.Promise.reject(createEnigmaError(errorCodes.SESSION_NOT_ATTACHED, 'Not attached')); } return _this2.Promise.resolve(); }); } /** * Function used to restore the global API. * @private * @param {Object} changed - A list where the restored APIs will be added. * @returns {Object} Returns a promise instance. */ }, { key: "restoreGlobal", value: function restoreGlobal(changed) { var global = this.apis.getApisByType('Global').pop(); changed.push(global.api); return this.Promise.resolve(); } /** * Function used to restore the doc API. * @private * @param {String} sessionState - The state of the session, attached or created. * @param {Array} closed - A list where the closed of APIs APIs will be added. * @param {Object} changed - A list where the restored APIs will be added. * @returns {Object} Returns a promise instance. */ }, { key: "restoreDoc", value: function restoreDoc(closed, changed) { var _this3 = this; var doc = this.apis.getApisByType('Doc').pop(); if (!doc) { return this.Promise.resolve(); } return this.rpc.send({ method: 'GetActiveDoc', handle: -1, params: [] }).then(function (response) { if (response.error && _this3.openDocParams) { return _this3.rpc.send({ method: 'OpenDoc', handle: -1, params: _this3.openDocParams }); } return response; }).then(function (response) { if (response.error) { closed.push(doc.api); return _this3.Promise.resolve(); } var handle = response.result.qReturn.qHandle; doc.api.handle = handle; changed.push(doc.api); return _this3.Promise.resolve(doc.api); }); } /** * Function used to restore the APIs on the doc. * @private * @param {Object} doc - The doc API on which the APIs we want to restore exist. * @param {Array} closed - A list where the closed of APIs APIs will be added. * @param {Object} changed - A list where the restored APIs will be added. * @returns {Object} Returns a promise instance. */ }, { key: "restoreDocObjects", value: function restoreDocObjects(doc, closed, changed) { var _this4 = this; var tasks = []; var apis = this.apis.getApis().map(function (entry) { return entry.api; }).filter(function (api) { return api.type !== 'Global' && api.type !== 'Doc'; }); if (!doc) { apis.forEach(function (api) { return closed.push(api); }); return this.Promise.resolve(); } apis.forEach(function (api) { var method = SuspendResume.buildGetMethodName(api.type); if (!method) { closed.push(api); } else { var request = _this4.rpc.send({ method: method, handle: doc.handle, params: [api.id] }).then(function (response) { if (response.error || !response.result.qReturn.qHandle) { closed.push(api); } else { api.handle = response.result.qReturn.qHandle; changed.push(api); } }); tasks.push(request); } }); return this.Promise.all(tasks); } /** * Set the instance as suspended. * @private * @param {Number} [code=4000] - The reason code for suspending the connection. * @param {String} [reason=""] - The human readable string describing * why the connection is suspended. */ }, { key: "suspend", value: function suspend() { var code = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : RPC_CLOSE_MANUAL_SUSPEND$1; var reason = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ''; this.isSuspended = true; return this.rpc.close(code, reason); } /** * Resumes a previously suspended RPC connection, and refreshes the API cache. * APIs unabled to be restored has their 'closed' * event triggered, otherwise 'changed'. * @private * @emits API#changed * @emits APIfunction@#closed * @param {Boolean} onlyIfAttached if true, resume only if the session was re-attached. * @returns {Promise} Eventually resolved if the RPC connection was successfully resumed, * otherwise rejected. */ }, { key: "resume", value: function resume(onlyIfAttached) { var _this5 = this; var changed = []; var closed = []; return this.restoreRpcConnection(onlyIfAttached).then(function () { return _this5.restoreGlobal(changed); }).then(function () { return _this5.restoreDoc(closed, changed); }).then(function (doc) { return _this5.restoreDocObjects(doc, closed, changed); }).then(function () { _this5.isSuspended = false; _this5.apis.clear(); closed.forEach(function (api) { api.emit('closed'); api.removeAllListeners(); }); changed.forEach(function (api) { _this5.apis.add(api.handle, api); if (api.type !== 'Global') { api.emit('changed'); } }); })["catch"](function (err) { return _this5.rpc.close().then(function () { return _this5.Promise.reject(err); }); }); } /** * Reopens the connection and waits for the OnConnected notification. * @private * @param {Number} timeout - The time to wait for the OnConnected notification. * @returns {Object} A promise containing the session state (SESSION_CREATED or SESSION_ATTACHED). */ }, { key: "reopen", value: function reopen(timeout) { var _this6 = this; var timer; var notificationResolve; var notificationReceived = false; var notificationPromise = new this.Promise(function (resolve) { notificationResolve = resolve; }); var waitForNotification = function waitForNotification() { if (!notificationReceived) { timer = setTimeout(function () { return notificationResolve('SESSION_CREATED'); }, timeout); } return notificationPromise; }; var onNotification = function onNotification(data) { if (data.method !== 'OnConnected') return; clearTimeout(timer); notificationResolve(data.params.qSessionState); notificationReceived = true; }; this.rpc.on('notification', onNotification); return this.rpc.open(true).then(waitForNotification).then(function (state) { _this6.rpc.removeListener('notification', onNotification); return state; })["catch"](function (err) { _this6.rpc.removeListener('notification', onNotification); return _this6.Promise.reject(err); }); } /** * Function used to build the get method names for Doc APIs. * @private * @param {String} type - The API type. * @returns {String} Returns the get method name, or undefined if the type cannot be restored. */ }], [{ key: "buildGetMethodName", value: function buildGetMethodName(type) { if (type === 'Field' || type === 'Variable') { return null; } if (type === 'GenericVariable') { return 'GetVariableById'; } return type.replace('Generic', 'Get'); } }]); return SuspendResume; }(); var SUCCESS_KEY = 'qSuccess'; function deltaRequestInterceptor(session, request) { var delta = session.config.protocol.delta && request.outKey !== -1 && request.outKey !== SUCCESS_KEY; if (delta) { request.delta = delta; } return request; } /** * Response interceptor for generating APIs. Handles the quirks of engine not * returning an error when an object is missing. * @private * @param {Session} session - The session the intercept is being executed on. * @param {Object} request - The JSON-RPC request. * @param {Object} response - The response. * @returns {Object} - Returns the generated API */ function apiResponseInterceptor(session, request, response) { if (response.qHandle && response.qType) { return session.getObjectApi({ handle: response.qHandle, type: response.qType, id: response.qGenericId, genericType: response.qGenericType }); } if (response.qHandle === null && response.qType === null) { var error = createEnigmaError(errorCodes.OBJECT_NOT_FOUND, 'Object not found'); return session.config.Promise.reject(error); } return response; } var hasOwn = Object.prototype.hasOwnProperty; var toStr = Object.prototype.toString; var defineProperty = Object.defineProperty; var gOPD = Object.getOwnPropertyDescriptor; var isArray = function isArray(arr) { if (typeof Array.isArray === 'function') { return Array.isArray(arr); } return toStr.call(arr) === '[object Array]'; }; var isPlainObject = function isPlainObject(obj) { if (!obj || toStr.call(obj) !== '[object Object]') { return false; } var hasOwnConstructor = hasOwn.call(obj, 'constructor'); var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf'); // Not own constructor property must be Object if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) { return false; } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. var key; for (key in obj) { /**/ } return typeof key === 'undefined' || hasOwn.call(obj, key); }; // If name is '__proto__', and Object.defineProperty is available, define __proto__ as an own property on target var setProperty = function setProperty(target, options) { if (defineProperty && options.name === '__proto__') { defineProperty(target, options.name, { enumerable: true, configurable: true, value: options.newValue, writable: true }); } else { target[options.name] = options.newValue; } }; // Return undefined instead of __proto__ if '__proto__' is not an own property var getProperty = function getProperty(obj, name) { if (name === '__proto__') { if (!hasOwn.call(obj, name)) { return void 0; } else if (gOPD) { // In early versions of node, obj['__proto__'] is buggy when obj has // __proto__ as an own property. Object.getOwnPropertyDescriptor() works. return gOPD(obj, name).value; } } return obj[name]; }; var extend = function extend() { var options, name, src, copy, copyIsArray, clone; var target = arguments[0]; var i = 1; var length = arguments.length; var deep = false; // Handle a deep copy situation if (typeof target === 'boolean') { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } if (target == null || (typeof target !== 'object' && typeof target !== 'function')) { target = {}; } for (; i < length; ++i) { options = arguments[i]; // Only deal with non-null/undefined values if (options != null) { // Extend the base object for (name in options) { src = getProperty(target, name); copy = getProperty(options, name); // Prevent never-ending loop if (target !== copy) { // Recurse if we're merging plain objects or arrays if (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) { if (copyIsArray) { copyIsArray = false; clone = src && isArray(src) ? src : []; } else { clone = src && isPlainObject(src) ? src : {}; } // Never move original objects, clone them setProperty(target, { name: name, newValue: extend(deep, clone, copy) }); // Don't bring in undefined values } else if (typeof copy !== 'undefined') { setProperty(target, { name: name, newValue: copy }); } } } } } // Return the modified object return target; }; function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } } function _typeof$2(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof$2 = function _typeof(obj) { return typeof obj; }; } else { _typeof$2 = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof$2(obj); } var extend$1 = extend.bind(null, true); var JSONPatch = {}; var isArray$1 = Array.isArray; function isObject(v) { return v != null && !Array.isArray(v) && _typeof$2(v) === 'object'; } function isUndef(v) { return typeof v === 'undefined'; } function isFunction(v) { return typeof v === 'function'; } /** * Generate an exact duplicate (with no references) of a specific value. * * @private * @param {Object} The value to duplicate * @returns {Object} a unique, duplicated value */ function generateValue(val) { if (val) { return extend$1({}, { val: val }).val; } return val; } /** * An additional type checker used to determine if the property is of internal * use or not a type that can be translated into JSON (like functions). * * @private * @param {Object} obj The object which has the property to check * @param {String} The property name to check * @returns {Boolean} Whether the property is deemed special or not */ function isSpecialProperty(obj, key) { return isFunction(obj[key]) || key.substring(0, 2) === '$$' || key.substring(0, 1) === '_'; } /** * Finds the parent object from a JSON-Pointer ("/foo/bar/baz" = "bar" is "baz" parent), * also creates the object structure needed. * * @private * @param {Object} data The root object to traverse through * @param {String} The JSON-Pointer string to use when traversing * @returns {Object} The parent object */ function getParent(data, str) { var seperator = '/'; var parts = str.substring(1).split(seperator).slice(0, -1); var numPart; parts.forEach(function (part, i) { if (i === parts.length) { return; } numPart = +part; var newPart = !isNaN(numPart) ? [] : {}; data[numPart || part] = isUndef(data[numPart || part]) ? newPart : data[part]; data = data[numPart || part]; }); return data; } /** * Cleans an object of all its properties, unless they're deemed special or * cannot be removed by configuration. * * @private * @param {Object} obj The object to clean */ function emptyObject(obj) { Object.keys(obj).forEach(function (key) { var config = Object.getOwnPropertyDescriptor(obj, key); if (config.configurable && !isSpecialProperty(obj, key)) { delete obj[key]; } }); } /** * Compare an object with another, could be object, array, number, string, bool. * @private * @param {Object} a The first object to compare * @param {Object} a The second object to compare * @returns {Boolean} Whether the objects are identical */ function compare(a, b) { var isIdentical = true; if (isObject(a) && isObject(b)) { if (Object.keys(a).length !== Object.keys(b).length) { return false; } Object.keys(a).forEach(function (key) { if (!compare(a[key], b[key])) { isIdentical = false; } }); return isIdentical; } if (isArray$1(a) && isArray$1(b)) { if (a.length !== b.length) { return false; } for (var i = 0, l = a.length; i < l; i += 1) { if (!compare(a[i], b[i])) { return false; } } return true; } return a === b; } /** * Generates patches by comparing two arrays. * * @private * @param {Array} oldA The old (original) array, which will be patched * @param {Array} newA The new array, which will be used to compare against * @returns {Array} An array of patches (if any) */ function patchArray(original, newA, basePath) { var patches = []; var oldA = original.slice(); var tmpIdx = -1; function findIndex(a, id, idx) { if (a[idx] && isUndef(a[idx].qInfo)) { return null; } if (a[idx] && a[idx].qInfo.qId === id) { // shortcut if identical return idx; } for (var ii = 0, ll = a.length; ii < ll; ii += 1) { if (a[ii] && a[ii].qInfo.qId === id) { return ii; } } return -1; } if (compare(newA, oldA)) { // array is unchanged return patches; } if (!isUndef(newA[0]) && isUndef(newA[0].qInfo)) { // we cannot create patches without unique identifiers, replace array... patches.push({ op: 'replace', path: basePath, value: newA }); return patches; } for (var i = oldA.length - 1; i >= 0; i -= 1) { tmpIdx = findIndex(newA, oldA[i].qInfo && oldA[i].qInfo.qId, i); if (tmpIdx === -1) { patches.push({ op: 'remove', path: "".concat(basePath, "/").concat(i) }); oldA.splice(i, 1); } else { patches = patches.concat(JSONPatch.generate(oldA[i], newA[tmpIdx], "".concat(basePath, "/").concat(i))); } } for (var _i = 0, l = newA.length; _i < l; _i += 1) { tmpIdx = findIndex(oldA, newA[_i].qInfo && newA[_i].qInfo.qId); if (tmpIdx === -1) { patches.push({ op: 'add', path: "".concat(basePath, "/").concat(_i), value: newA[_i] }); oldA.splice(_i, 0, newA[_i]); } else if (tmpIdx !== _i) { patches.push({ op: 'move', path: "".concat(basePath, "/").concat(_i), from: "".concat(basePath, "/").concat(tmpIdx) }); oldA.splice(_i, 0, oldA.splice(tmpIdx, 1)[0]); } } return patches; } /** * Generate an array of JSON-Patch:es following the JSON-Patch Specification Draft. * * See [specification draft](http://tools.ietf.org/html/draft-ietf-appsawg-json-patch-10) * * Does NOT currently generate patches for arrays (will replace them) * @private * @param {Object} original The object to patch to * @param {Object} newData The object to patch from * @param {String} [basePath] The base path to use when generating the paths for * the patches (normally not used) * @returns {Array} An array of patches */ JSONPatch.generate = function generate(original, newData, basePath) { basePath = basePath || ''; var patches = []; Object.keys(newData).forEach(function (key) { var val = generateValue(newData[key]); var oldVal = original[key]; var tmpPath = "".concat(basePath, "/").concat(key); if (compare(val, oldVal) || isSpecialProperty(newData, key)) { return; } if (isUndef(oldVal)) { // property does not previously exist patches.push({ op: 'add', path: tmpPath, value: val }); } else if (isObject(val) && isObject(oldVal)) { // we need to generate sub-patches for this, since it already exist patches = patches.concat(JSONPatch.generate(oldVal, val, tmpPath)); } else if (isArray$1(val) && isArray$1(oldVal)) { patches = patches.concat(patchArray(oldVal, val, tmpPath)); } else { // it's a simple property (bool, string, number) patches.push({ op: 'replace', path: "".concat(basePath, "/").concat(key), value: val }); } }); Object.keys(original).forEach(function (key) { if (isUndef(newData[key]) && !isSpecialProperty(original, key)) { // this property does not exist anymore patches.push({ op: 'remove', path: "".concat(basePath, "/").concat(key) }); } }); return patches; }; /** * Apply a list of patches to an object. * @private * @param {Object} original The object to patch * @param {Array} patches The list of patches to apply */ JSONPatch.apply = function apply(original, patches) { patches.forEach(function (patch) { var parent = getParent(original, patch.path); var key = patch.path.split('/').splice(-1)[0]; var target = key && isNaN(+key) ? parent[key] : parent[+key] || parent; var from = patch.from ? patch.from.split('/').splice(-1)[0] : null; if (patch.path === '/') { parent = null; target = original; } if (patch.op === 'add' || patch.op === 'replace') { if (isArray$1(parent)) { // trust indexes from patches, so don't replace the index if it's an add if (key === '-') { key = parent.length; } parent.splice(+key, patch.op === 'add' ? 0 : 1, patch.value); } else if (isArray$1(target) && isArray$1(patch.value)) { var _target; var newValues = patch.value.slice(); // keep array reference if possible... target.length = 0; (_target = target).push.apply(_target, _toConsumableArray(newValues)); } else if (isObject(target) && isObject(patch.value)) { // keep object reference if possible... emptyObject(target); extend$1(target, patch.value); } else if (!parent) { throw createEnigmaError(errorCodes.PATCH_HAS_NO_PARENT, 'Patchee is not an object we can patch'); } else { // simple value parent[key] = patch.value; } } else if (patch.op === 'move') { var oldParent = getParent(original, patch.from); if (isArray$1(parent)) { parent.splice(+key, 0, oldParent.splice(+from, 1)[0]); } else { parent[key] = oldParent[from]; delete oldParent[from]; } } else if (patch.op === 'remove') { if (isArray$1(parent)) { parent.splice(+key, 1); } else { delete parent[key]; } } }); }; /** * Deep clone an object. * @private * @param {Object} obj The object to clone * @returns {Object} A new object identical to the `obj` */ JSONPatch.clone = function clone(obj) { return extend$1({}, obj); }; /** * Creates a JSON-patch. * @private * @param {String} op The operation of the patch. Available values: "add", "remove", "move" * @param {Object} [val] The value to set the `path` to. If `op` is `move`, `val` * is the "from JSON-path" path * @param {String} path The JSON-path for the property to change (e.g. "/qHyperCubeDef/columnOrder") * @returns {Object} A patch following the JSON-patch specification */ JSONPatch.createPatch = function createPatch(op, val, path) { var patch = { op: op.toLowerCase(), path: path }; if (patch.op === 'move') { patch.from = val; } else if (typeof val !== 'undefined') { patch.value = val; } return patch; }; /** * Apply the differences of two objects (keeping references if possible). * Identical to running `JSONPatch.apply(original, JSONPatch.generate(original, newData));` * @private * @param {Object} original The object to update/patch * @param {Object} newData the object to diff against * * @example * var obj1 = { foo: [1,2,3], bar: { baz: true, qux: 1 } }; * var obj2 = { foo: [4,5,6], bar: { baz: false } }; * JSONPatch.updateObject(obj1, obj2); * // => { foo: [4,5,6], bar: { baz: false } }; */ JSONPatch.updateObject = function updateObject(original, newData) { if (!Object.keys(original).length) { extend$1(original, newData); return; } JSONPatch.apply(original, JSONPatch.generate(original, newData)); }; function _typeof$3(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof$3 = function _typeof(obj) { return typeof obj; }; } else { _typeof$3 = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof$3(obj); } var sessions = {}; /** * Function to make sure we release handle caches when they are closed. * @private * @param {Session} session The session instance to listen on. */ var bindSession = function bindSession(session) { if (!sessions[session.id]) { var cache = {}; sessions[session.id] = cache; session.on('traffic:received', function (data) { return data.close && data.close.forEach(function (handle) { return delete cache[handle]; }); }); session.on('closed', function () { return delete sessions[session.id]; }); } }; /** * Simple function that ensures the session events has been bound, and returns * either an existing key-value cache or creates one for the specified handle. * @private * @param {Session} session The session that owns the handle. * @param {Number} handle The object handle to retrieve the cache for. * @returns {KeyValueCache} The cache instance. */ var getHandleCache = function getHandleCache(session, handle) { bindSession(session); var cache = sessions[session.id]; if (!cache[handle]) { cache[handle] = new KeyValueCache(); } return cache[handle]; }; /** * Function used to apply a list of patches and return the patched value. * @private * @param {Session} session The session. * @param {Number} handle The object handle. * @param {String} cacheId The cacheId. * @param {Array} patches The patches. * @returns {Object} Returns the patched value. */ var patchValue = function patchValue(session, handle, cacheId, patches) { var cache = getHandleCache(session, handle); var entry = cache.get(cacheId); if (typeof entry === 'undefined') { entry = Array.isArray(patches[0].value) ? [] : {}; } if (patches.length) { if (patches[0].path === '/' && _typeof$3(patches[0].value) !== 'object') { // 'plain' values on root path is not supported (no object reference), // so we simply store the value directly: entry = patches[0].value; } else { JSONPatch.apply(entry, patches); } cache.set(cacheId, entry); } return entry; }; /** * Process delta interceptor. * @private * @param {Session} session The session the intercept is being executed on. * @param {Object} request The JSON-RPC request. * @param {Object} response The response. * @returns {Object} Returns the patched response */ function deltaResponseInterceptor(session, request, response) { var delta = response.delta, result = response.result; if (delta) { // when delta is on the response data is expected to be an array of patches: Object.keys(result).forEach(function (key) { if (!Array.isArray(result[key])) { throw createEnigmaError(errorCodes.EXPECTED_ARRAY_OF_PATCHES, 'Unexpected RPC response, expected array of patches'); } result[key] = patchValue(session, request.handle, "".concat(request.method, "-").concat(key), result[key]); }); // return a cloned response object to avoid patched object references: return JSON.parse(JSON.stringify(response)); } return response; } // export object reference for testing purposes: deltaResponseInterceptor.sessions = sessions; /** * Process error interceptor. * @private * @param {Session} session - The session the intercept is being executed on. * @param {Object} request - The JSON-RPC request. * @param {Object} response - The response. * @returns {Object} - Returns the defined error for an error, else the response. */ function errorResponseInterceptor(session, request, response) { if (typeof response.error !== 'undefined') { var data = response.error; var error = new Error(data.message); error.code = data.code; error.parameter = data.parameter; return session.config.Promise.reject(error); } return response; } var RETURN_KEY = 'qReturn'; /** * Picks out the result "out" parameter based on the QIX method+schema, with * some specific handling for some methods that breaks the predictable protocol. * @private * @param {Session} session - The session the intercept is being executed on. * @param {Object} request - The JSON-RPC request. * @param {Object} response - The response. * @returns {Object} - Returns the result property on the response */ function outParamResponseInterceptor(session, request, response) { if (request.method === 'CreateSessionApp' || request.method === 'CreateSessionAppFromApp') { // this method returns multiple out params that we need // to normalize before processing the response further: response[RETURN_KEY].qGenericId = response.qSessionAppId || response[RETURN_KEY].qGenericId; } else if (request.method === 'GetInteract') { // this method returns a qReturn value when it should only return // meta.outKey: delete response[RETURN_KEY]; } if (hasOwnProperty.call(response, RETURN_KEY)) { return response[RETURN_KEY]; } if (request.outKey !== -1) { return response[request.outKey]; } return response; } /** * Process result interceptor. * @private * @param {Session} session - The session the intercept is being executed on. * @param {Object} request - The JSON-RPC request. * @param {Object} response - The response. * @returns {Object} - Returns the result property on the response */ function resultResponseInterceptor(session, request, response) { return response.result; } function _toConsumableArray$1(arr) { return _arrayWithoutHoles$1(arr) || _iterableToArray$1(arr) || _nonIterableSpread$1(); } function _nonIterableSpread$1() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } function _iterableToArray$1(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } function _arrayWithoutHoles$1(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } } function _classCallCheck$7(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties$6(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass$6(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties$6(Constructor.prototype, protoProps); if (staticProps) _defineProperties$6(Constructor, staticProps); return Constructor; } /** * Interceptors is a concept similar to mixins, but run on a lower level. The interceptor concept * can augment either the requests (i.e. before sent to QIX Engine), or the responses (i.e. after * QIX Engine has sent a response). The interceptor promises runs in parallel to the regular * promises used in enigma.js, which means that it can be really useful when you want to normalize * behaviors in your application. * @interface Interceptor */ /** * @class InterceptorRequest * @implements {Interceptor} */ /** * @class InterceptorResponse * @implements {Interceptor} */ /** * This method is invoked when a request is about to be sent to QIX Engine. * @function InterceptorRequest#onFulfilled * @param {Session} session The session executing the interceptor. * @param {Object} request The JSON-RPC request that will be sent. */ /** * This method is invoked when a previous interceptor has rejected the * promise, use this to handle for example errors before they are sent into mixins. * @function InterceptorResponse#onRejected * @param {Session} session The session executing the interceptor. You may use .retry() to retry * sending it to QIX Engine. * @param {Object} request The JSON-RPC request resulting in this error. * @param {Object} error Whatever the previous interceptor is rejected with. */ /** * This method is invoked when a promise has been successfully resolved, * use this to modify the result or reject the promise chain before it is sent * to mixins. * @function InterceptorResponse#onFulfilled * @param {Session} session The session executing the interceptor. * @param {Object} request The JSON-RPC request resulting in this response. * @param {Object} result Whatever the previous interceptor is resolved with. */ var Intercept = /*#__PURE__*/ function () { /** * Create a new Intercept instance. * @private * @param {Object} options The configuration options for this class. * @param {Promise} options.Promise The promise constructor to use. * @param {ApiCache} options.apis The ApiCache instance to use. * @param {Array} [options.request] The additional request interceptors to use. * @param {Array} [options.response] The additional response interceptors to use. */ function Intercept(options) { _classCallCheck$7(this, Intercept); Object.assign(this, options); this.request = [{ onFulfilled: deltaRequestInterceptor }].concat(_toConsumableArray$1(this.request || [])); this.response = [{ onFulfilled: errorResponseInterceptor }, { onFulfilled: deltaResponseInterceptor }, { onFulfilled: resultResponseInterceptor }, { onFulfilled: outParamResponseInterceptor }].concat(_toConsumableArray$1(this.response || []), [{ onFulfilled: apiResponseInterceptor }]); } /** * Execute the request interceptor queue, each interceptor will get the result from * the previous interceptor. * @private * @param {Session} session The session instance to execute against. * @param {Promise} promise The promise to chain on to. * @returns {Promise} */ _createClass$6(Intercept, [{ key: "executeRequests", value: function executeRequests(session, promise) { var _this = this; return this.request.reduce(function (interception, interceptor) { var intercept = interceptor.onFulfilled && interceptor.onFulfilled.bind(_this, session); return interception.then(intercept); }, promise); } /** * Execute the response interceptor queue, each interceptor will get the result from * the previous interceptor. * @private * @param {Session} session The session instance to execute against. * @param {Promise} promise The promise to chain on to. * @param {Object} request The JSONRPC request object for the intercepted response. * @returns {Promise} */ }, { key: "executeResponses", value: function executeResponses(session, promise, request) { var _this2 = this; return this.response.reduce(function (interception, interceptor) { return interception.then(interceptor.onFulfilled && interceptor.onFulfilled.bind(_this2, session, request), interceptor.onRejected && interceptor.onRejected.bind(_this2, session, request)); }, promise); } }]); return Intercept; }(); function _typeof$4(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof$4 = function _typeof(obj) { return typeof obj; }; } else { _typeof$4 = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof$4(obj); } function _classCallCheck$8(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties$7(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass$7(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties$7(Constructor.prototype, protoProps); if (staticProps) _defineProperties$7(Constructor, staticProps); return Constructor; } function _possibleConstructorReturn$1(self, call) { if (call && (_typeof$4(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized$1(self); } function _assertThisInitialized$1(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); } function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf$1(object); if (object === null) break; } return object; } function _getPrototypeOf$1(o) { _getPrototypeOf$1 = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf$1(o); } function _inherits$1(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf$1(subClass, superClass); } function _setPrototypeOf$1(o, p) { _setPrototypeOf$1 = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf$1(o, p); } /** * API cache for instances of QIX types, e.g. GenericObject. * @private * @extends KeyValueCache */ var ApiCache = /*#__PURE__*/ function (_KeyValueCache) { _inherits$1(ApiCache, _KeyValueCache); function ApiCache() { _classCallCheck$8(this, ApiCache); return _possibleConstructorReturn$1(this, _getPrototypeOf$1(ApiCache).apply(this, arguments)); } _createClass$7(ApiCache, [{ key: "add", /** * Adds an API. * @private * @function ApiCache#add * @param {Number} handle - The handle for the API. * @param {*} api - The API. * @returns {{api: *}} The entry. */ value: function add(handle, api) { var _this = this; var entry = { api: api }; _get(_getPrototypeOf$1(ApiCache.prototype), "add", this).call(this, handle.toString(), entry); api.on('closed', function () { return _this.remove(handle); }); return entry; } /** * Gets an API. * @private * @function ApiCache#getApi * @param {Number} handle - The handle for the API. * @returns {*} The API for the handle. */ }, { key: "getApi", value: function getApi(handle) { var entry = typeof handle !== 'undefined' ? this.get(handle.toString()) : undefined; return entry && entry.api; } /** * Gets a list of APIs. * @private * @function ApiCache#getApis * @returns {Array} The list of entries including `handle` and `api` properties for each entry. */ }, { key: "getApis", value: function getApis() { return _get(_getPrototypeOf$1(ApiCache.prototype), "getAll", this).call(this).map(function (entry) { return { handle: entry.key, api: entry.value.api }; }); } /** * Gets a list of APIs with a given type. * @private * @function ApiCache#getApisByType * @param {String} type - The type of APIs to get. * @returns {Array} The list of entries including `handle` and `api` properties for each entry. */ }, { key: "getApisByType", value: function getApisByType(type) { return this.getApis().filter(function (entry) { return entry.api.type === type; }); } }]); return ApiCache; }(KeyValueCache); function _classCallCheck$9(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties$8(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass$8(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties$8(Constructor.prototype, protoProps); if (staticProps) _defineProperties$8(Constructor, staticProps); return Constructor; } /** * The enigma.js configuration object. * @interface Configuration * @property {Object} schema Object containing the specification for the API to generate. * Corresponds to a specific version of the QIX Engine API. * @property {String} url String containing a proper websocker URL to QIX Engine. * @property {Function} [createSocket] A function to use when instantiating the WebSocket, * mandatory for Node.js. * @property {Object} [Promise] ES6-compatible Promise library. * @property {Boolean} [suspendOnClose=false] Set to true if the session should be suspended * instead of closed when the websocket is closed. * @property {Array} [mixins=[]] Mixins to extend/augment the QIX Engine API. Mixins * are applied in the array order. * @property {Array} [requestInterceptors=[]] Interceptors for augmenting requests before they * are sent to QIX Engine. Interceptors are applied in the array order. * @property {Array} [responseInterceptors=[]] Interceptors for augmenting responses before they * are passed into mixins and end-users. Interceptors are applied in the array order. * @property {Object} [protocol={}] An object containing additional JSON-RPC request parameters. * @property {Boolean} [protocol.delta=true] Set to false to disable the use of the * bandwidth-reducing delta protocol. */ /** * Mixin object to extend/augment the QIX Engine API * @interface Mixin * @property {String|Array} types String or array of strings containing the API-types that * will be mixed in. * @property {Object} [extend] Object literal containing the methods that will be extended on the * specified API. * @property {Object} [override] Object literal containing the methods to override existing methods. * @property {Function} [init] Init function that, if defined, will run when an API is instantiated. * It runs with Promise and API object as parameters */ /** * The API for generated APIs depends on the QIX Engine schema you pass into your Configuration, * and on what QIX struct the API has. * @interface API * @property {String} id Contains the unique identifier for this API. * @property {String} type Contains the schema class name for this API. * @property {String} genericType Corresponds to the qInfo.qType property on the generic object's * properties object. * @property {Session} session Contains a reference to the session that this API belongs to. * @property {Number} handle Contains the handle QIX Engine assigned to the API. Used interally in * enigma.js for caches and JSON-RPC requests. */ /** * Handle changes on the API. The changed event is triggered whenever enigma.js or QIX Engine has * identified potential changes on the underlying properties or hypercubes and you should re-fetch * your data. * @event API#changed * @type {Object} */ /** * Handle closed API. The closed event is triggered whenever QIX Engine considers an API closed. * It usually means that it no longer exist in the QIX Engine document or session. * @event API#closed * @type {Object} */ /** * Handle JSON-RPC requests/responses for this API. Generally used in debugging purposes. * traffic:* will handle all websocket messages, traffic:sent will handle outgoing messages * and traffic:received will handle incoming messages. * @event API#traffic * @type {Object} */ /** * Qix service. */ var Qix = /*#__PURE__*/ function () { function Qix() { _classCallCheck$9(this, Qix); } _createClass$8(Qix, null, [{ key: "getSession", /** * Function used to get a session. * @private * @param {Configuration} config The configuration object for this session. * @returns {Session} Returns a session instance. */ value: function getSession(config) { var createSocket = config.createSocket, Promise = config.Promise, requestInterceptors = config.requestInterceptors, responseInterceptors = config.responseInterceptors, url = config.url; var apis = new ApiCache(); var intercept = new Intercept({ apis: apis, Promise: Promise, request: requestInterceptors, response: responseInterceptors }); var rpc = new RPC({ createSocket: createSocket, Promise: Promise, url: url }); var suspendResume = new SuspendResume({ apis: apis, Promise: Promise, rpc: rpc }); var session = new Session({ apis: apis, config: config, intercept: intercept, rpc: rpc, suspendResume: suspendResume }); return session; } /** * Function used to create a QIX session. * @param {Configuration} config The configuration object for the QIX session. * @returns {Session} Returns a new QIX session. */ }, { key: "create", value: function create(config) { Qix.configureDefaults(config); config.mixins.forEach(function (mixin) { config.definition.registerMixin(mixin); }); return Qix.getSession(config); } /** * Function used to configure defaults. * @private * @param {Configuration} config The configuration object for how to connect * and retrieve end QIX APIs. */ }, { key: "configureDefaults", value: function configureDefaults(config) { if (!config) { throw createEnigmaError(errorCodes.NO_CONFIG_SUPPLIED, 'You need to supply a configuration.'); } // eslint-disable-next-line no-restricted-globals if (!config.Promise && typeof Promise === 'undefined') { throw createEnigmaError(errorCodes.PROMISE_REQUIRED, 'Your environment has no Promise implementation. You must provide a Promise implementation in the config.'); } if (typeof config.createSocket !== 'function' && typeof WebSocket === 'function') { // eslint-disable-next-line no-undef config.createSocket = function (url) { return new WebSocket(url); }; } if (typeof config.suspendOnClose === 'undefined') { config.suspendOnClose = false; } config.protocol = config.protocol || {}; config.protocol.delta = typeof config.protocol.delta !== 'undefined' ? config.protocol.delta : true; // eslint-disable-next-line no-restricted-globals config.Promise = config.Promise || Promise; config.mixins = config.mixins || []; config.definition = config.definition || new Schema(config); } }]); return Qix; }(); return Qix; }))); //# sourceMappingURL=enigma.js.map /***/ }), /* 91 */ /***/ (function(module) { module.exports = JSON.parse("{\"structs\":{\"Field\":{\"GetCardinal\":{\"In\":[],\"Out\":[]},\"GetAndMode\":{\"In\":[],\"Out\":[]},\"SelectValues\":{\"In\":[{\"Name\":\"qFieldValues\",\"DefaultValue\":[{\"qText\":\"\",\"qIsNumeric\":false,\"qNumber\":0}]},{\"Name\":\"qToggleMode\",\"DefaultValue\":false,\"Optional\":true},{\"Name\":\"qSoftLock\",\"DefaultValue\":false,\"Optional\":true}],\"Out\":[]},\"Select\":{\"In\":[{\"Name\":\"qMatch\",\"DefaultValue\":\"\"},{\"Name\":\"qSoftLock\",\"DefaultValue\":false,\"Optional\":true},{\"Name\":\"qExcludedValuesMode\",\"DefaultValue\":0,\"Optional\":true}],\"Out\":[]},\"ToggleSelect\":{\"In\":[{\"Name\":\"qMatch\",\"DefaultValue\":\"\"},{\"Name\":\"qSoftLock\",\"DefaultValue\":false,\"Optional\":true},{\"Name\":\"qExcludedValuesMode\",\"DefaultValue\":0,\"Optional\":true}],\"Out\":[]},\"ClearAllButThis\":{\"In\":[{\"Name\":\"qSoftLock\",\"DefaultValue\":false,\"Optional\":true}],\"Out\":[]},\"SelectPossible\":{\"In\":[{\"Name\":\"qSoftLock\",\"DefaultValue\":false,\"Optional\":true}],\"Out\":[]},\"SelectExcluded\":{\"In\":[{\"Name\":\"qSoftLock\",\"DefaultValue\":false,\"Optional\":true}],\"Out\":[]},\"SelectAll\":{\"In\":[{\"Name\":\"qSoftLock\",\"DefaultValue\":false,\"Optional\":true}],\"Out\":[]},\"Lock\":{\"In\":[],\"Out\":[]},\"Unlock\":{\"In\":[],\"Out\":[]},\"GetNxProperties\":{\"In\":[],\"Out\":[{\"Name\":\"qProperties\"}]},\"SetNxProperties\":{\"In\":[{\"Name\":\"qProperties\",\"DefaultValue\":{\"qOneAndOnlyOne\":false}}],\"Out\":[]},\"SetAndMode\":{\"In\":[{\"Name\":\"qAndMode\",\"DefaultValue\":false}],\"Out\":[]},\"SelectAlternative\":{\"In\":[{\"Name\":\"qSoftLock\",\"DefaultValue\":false,\"Optional\":true}],\"Out\":[]},\"LowLevelSelect\":{\"In\":[{\"Name\":\"qValues\",\"DefaultValue\":[0]},{\"Name\":\"qToggleMode\",\"DefaultValue\":false},{\"Name\":\"qSoftLock\",\"DefaultValue\":false,\"Optional\":true}],\"Out\":[]},\"Clear\":{\"In\":[],\"Out\":[]}},\"Variable\":{\"GetContent\":{\"In\":[],\"Out\":[{\"Name\":\"qContent\"}]},\"GetRawContent\":{\"In\":[],\"Out\":[]},\"SetContent\":{\"In\":[{\"Name\":\"qContent\",\"DefaultValue\":\"\"},{\"Name\":\"qUpdateMRU\",\"DefaultValue\":false}],\"Out\":[]},\"ForceContent\":{\"In\":[{\"Name\":\"qs\",\"DefaultValue\":\"\"},{\"Name\":\"qd\",\"DefaultValue\":0}],\"Out\":[]},\"GetNxProperties\":{\"In\":[],\"Out\":[{\"Name\":\"qProperties\"}]},\"SetNxProperties\":{\"In\":[{\"Name\":\"qProperties\",\"DefaultValue\":{\"qName\":\"\",\"qNumberPresentation\":{\"qType\":0,\"qnDec\":0,\"qUseThou\":0,\"qFmt\":\"\",\"qDec\":\"\",\"qThou\":\"\"},\"qIncludeInBookmark\":false,\"qUsePredefListedValues\":false,\"qPreDefinedList\":[\"\"]}}],\"Out\":[]}},\"GenericObject\":{\"GetLayout\":{\"In\":[],\"Out\":[{\"Name\":\"qLayout\"}]},\"GetListObjectData\":{\"In\":[{\"Name\":\"qPath\",\"DefaultValue\":\"\"},{\"Name\":\"qPages\",\"DefaultValue\":[{\"qLeft\":0,\"qTop\":0,\"qWidth\":0,\"qHeight\":0}]}],\"Out\":[{\"Name\":\"qDataPages\"}]},\"GetHyperCubeData\":{\"In\":[{\"Name\":\"qPath\",\"DefaultValue\":\"\"},{\"Name\":\"qPages\",\"DefaultValue\":[{\"qLeft\":0,\"qTop\":0,\"qWidth\":0,\"qHeight\":0}]}],\"Out\":[{\"Name\":\"qDataPages\"}]},\"GetHyperCubeReducedData\":{\"In\":[{\"Name\":\"qPath\",\"DefaultValue\":\"\"},{\"Name\":\"qPages\",\"DefaultValue\":[{\"qLeft\":0,\"qTop\":0,\"qWidth\":0,\"qHeight\":0}]},{\"Name\":\"qZoomFactor\",\"DefaultValue\":0},{\"Name\":\"qReductionMode\",\"DefaultValue\":0}],\"Out\":[{\"Name\":\"qDataPages\"}]},\"GetHyperCubePivotData\":{\"In\":[{\"Name\":\"qPath\",\"DefaultValue\":\"\"},{\"Name\":\"qPages\",\"DefaultValue\":[{\"qLeft\":0,\"qTop\":0,\"qWidth\":0,\"qHeight\":0}]}],\"Out\":[{\"Name\":\"qDataPages\"}]},\"GetHyperCubeStackData\":{\"In\":[{\"Name\":\"qPath\",\"DefaultValue\":\"\"},{\"Name\":\"qPages\",\"DefaultValue\":[{\"qLeft\":0,\"qTop\":0,\"qWidth\":0,\"qHeight\":0}]},{\"Name\":\"qMaxNbrCells\",\"DefaultValue\":0,\"Optional\":true}],\"Out\":[{\"Name\":\"qDataPages\"}]},\"GetHyperCubeContinuousData\":{\"In\":[{\"Name\":\"qPath\",\"DefaultValue\":\"\"},{\"Name\":\"qOptions\",\"DefaultValue\":{\"qStart\":0,\"qEnd\":0,\"qNbrPoints\":0,\"qMaxNbrTicks\":0,\"qMaxNumberLines\":0}},{\"Name\":\"qReverseSort\",\"DefaultValue\":false,\"Optional\":true}],\"Out\":[{\"Name\":\"qDataPages\"},{\"Name\":\"qAxisData\"}]},\"GetHyperCubeTreeData\":{\"In\":[{\"Name\":\"qPath\",\"DefaultValue\":\"\"},{\"Name\":\"qNodeOptions\",\"DefaultValue\":{\"qMaxNbrOfNodes\":0,\"qTreeNodes\":[{\"qArea\":{\"qLeft\":0,\"qTop\":0,\"qWidth\":0,\"qHeight\":0},\"qAllValues\":false}],\"qTreeLevels\":{\"qLeft\":0,\"qDepth\":0}},\"Optional\":true}],\"Out\":[{\"Name\":\"qNodes\"}]},\"GetHyperCubeBinnedData\":{\"In\":[{\"Name\":\"qPath\",\"DefaultValue\":\"\"},{\"Name\":\"qPages\",\"DefaultValue\":[{\"qLeft\":0,\"qTop\":0,\"qWidth\":0,\"qHeight\":0}]},{\"Name\":\"qViewport\",\"DefaultValue\":{\"qWidth\":0,\"qHeight\":0,\"qZoomLevel\":0}},{\"Name\":\"qDataRanges\",\"DefaultValue\":[{\"qLeft\":0,\"qTop\":0,\"qWidth\":0,\"qHeight\":0}]},{\"Name\":\"qMaxNbrCells\",\"DefaultValue\":0},{\"Name\":\"qQueryLevel\",\"DefaultValue\":0},{\"Name\":\"qBinningMethod\",\"DefaultValue\":0}],\"Out\":[{\"Name\":\"qDataPages\"}]},\"ApplyPatches\":{\"In\":[{\"Name\":\"qPatches\",\"DefaultValue\":[{\"qOp\":0,\"qPath\":\"\",\"qValue\":\"\"}]},{\"Name\":\"qSoftPatch\",\"DefaultValue\":false,\"Optional\":true}],\"Out\":[]},\"ClearSoftPatches\":{\"In\":[],\"Out\":[]},\"SetProperties\":{\"In\":[{\"Name\":\"qProp\",\"DefaultValue\":{\"qInfo\":{\"qId\":\"\",\"qType\":\"\"},\"qExtendsId\":\"\",\"qMetaDef\":{}}}],\"Out\":[]},\"GetProperties\":{\"In\":[],\"Out\":[{\"Name\":\"qProp\"}]},\"GetEffectiveProperties\":{\"In\":[],\"Out\":[{\"Name\":\"qProp\"}]},\"SetFullPropertyTree\":{\"In\":[{\"Name\":\"qPropEntry\",\"DefaultValue\":{\"qProperty\":{\"qInfo\":{\"qId\":\"\",\"qType\":\"\"},\"qExtendsId\":\"\",\"qMetaDef\":{}},\"qChildren\":[],\"qEmbeddedSnapshotRef\":null}}],\"Out\":[]},\"GetFullPropertyTree\":{\"In\":[],\"Out\":[{\"Name\":\"qPropEntry\"}]},\"GetInfo\":{\"In\":[],\"Out\":[{\"Name\":\"qInfo\"}]},\"ClearSelections\":{\"In\":[{\"Name\":\"qPath\",\"DefaultValue\":\"\"},{\"Name\":\"qColIndices\",\"DefaultValue\":[0],\"Optional\":true}],\"Out\":[]},\"ExportData\":{\"In\":[{\"Name\":\"qFileType\",\"DefaultValue\":0},{\"Name\":\"qPath\",\"DefaultValue\":\"\",\"Optional\":true},{\"Name\":\"qFileName\",\"DefaultValue\":\"\",\"Optional\":true},{\"Name\":\"qExportState\",\"DefaultValue\":0,\"Optional\":true}],\"Out\":[{\"Name\":\"qUrl\"},{\"Name\":\"qWarnings\"}]},\"SelectListObjectValues\":{\"In\":[{\"Name\":\"qPath\",\"DefaultValue\":\"\"},{\"Name\":\"qValues\",\"DefaultValue\":[0]},{\"Name\":\"qToggleMode\",\"DefaultValue\":false},{\"Name\":\"qSoftLock\",\"DefaultValue\":false,\"Optional\":true}],\"Out\":[{\"Name\":\"qSuccess\"}]},\"SelectListObjectPossible\":{\"In\":[{\"Name\":\"qPath\",\"DefaultValue\":\"\"},{\"Name\":\"qSoftLock\",\"DefaultValue\":false,\"Optional\":true}],\"Out\":[{\"Name\":\"qSuccess\"}]},\"SelectListObjectExcluded\":{\"In\":[{\"Name\":\"qPath\",\"DefaultValue\":\"\"},{\"Name\":\"qSoftLock\",\"DefaultValue\":false,\"Optional\":true}],\"Out\":[{\"Name\":\"qSuccess\"}]},\"SelectListObjectAlternative\":{\"In\":[{\"Name\":\"qPath\",\"DefaultValue\":\"\"},{\"Name\":\"qSoftLock\",\"DefaultValue\":false,\"Optional\":true}],\"Out\":[{\"Name\":\"qSuccess\"}]},\"SelectListObjectAll\":{\"In\":[{\"Name\":\"qPath\",\"DefaultValue\":\"\"},{\"Name\":\"qSoftLock\",\"DefaultValue\":false,\"Optional\":true}],\"Out\":[{\"Name\":\"qSuccess\"}]},\"SelectListObjectContinuousRange\":{\"In\":[{\"Name\":\"qPath\",\"DefaultValue\":\"\"},{\"Name\":\"qRanges\",\"DefaultValue\":[{\"qMin\":0,\"qMax\":0,\"qMinInclEq\":false,\"qMaxInclEq\":false}]},{\"Name\":\"qSoftLock\",\"DefaultValue\":false,\"Optional\":true}],\"Out\":[{\"Name\":\"qSuccess\"}]},\"SearchListObjectFor\":{\"In\":[{\"Name\":\"qPath\",\"DefaultValue\":\"\"},{\"Name\":\"qMatch\",\"DefaultValue\":\"\"}],\"Out\":[{\"Name\":\"qSuccess\"}]},\"AbortListObjectSearch\":{\"In\":[{\"Name\":\"qPath\",\"DefaultValue\":\"\"}],\"Out\":[]},\"AcceptListObjectSearch\":{\"In\":[{\"Name\":\"qPath\",\"DefaultValue\":\"\"},{\"Name\":\"qToggleMode\",\"DefaultValue\":false},{\"Name\":\"qSoftLock\",\"DefaultValue\":false,\"Optional\":true}],\"Out\":[]},\"ExpandLeft\":{\"In\":[{\"Name\":\"qPath\",\"DefaultValue\":\"\"},{\"Name\":\"qRow\",\"DefaultValue\":0},{\"Name\":\"qCol\",\"DefaultValue\":0},{\"Name\":\"qAll\",\"DefaultValue\":false}],\"Out\":[]},\"ExpandTop\":{\"In\":[{\"Name\":\"qPath\",\"DefaultValue\":\"\"},{\"Name\":\"qRow\",\"DefaultValue\":0},{\"Name\":\"qCol\",\"DefaultValue\":0},{\"Name\":\"qAll\",\"DefaultValue\":false}],\"Out\":[]},\"CollapseLeft\":{\"In\":[{\"Name\":\"qPath\",\"DefaultValue\":\"\"},{\"Name\":\"qRow\",\"DefaultValue\":0},{\"Name\":\"qCol\",\"DefaultValue\":0},{\"Name\":\"qAll\",\"DefaultValue\":false}],\"Out\":[]},\"CollapseTop\":{\"In\":[{\"Name\":\"qPath\",\"DefaultValue\":\"\"},{\"Name\":\"qRow\",\"DefaultValue\":0},{\"Name\":\"qCol\",\"DefaultValue\":0},{\"Name\":\"qAll\",\"DefaultValue\":false}],\"Out\":[]},\"DrillUp\":{\"In\":[{\"Name\":\"qPath\",\"DefaultValue\":\"\"},{\"Name\":\"qDimNo\",\"DefaultValue\":0},{\"Name\":\"qNbrSteps\",\"DefaultValue\":0}],\"Out\":[]},\"Lock\":{\"In\":[{\"Name\":\"qPath\",\"DefaultValue\":\"\"},{\"Name\":\"qColIndices\",\"DefaultValue\":[0],\"Optional\":true}],\"Out\":[]},\"Unlock\":{\"In\":[{\"Name\":\"qPath\",\"DefaultValue\":\"\"},{\"Name\":\"qColIndices\",\"DefaultValue\":[0],\"Optional\":true}],\"Out\":[]},\"SelectHyperCubeValues\":{\"In\":[{\"Name\":\"qPath\",\"DefaultValue\":\"\"},{\"Name\":\"qDimNo\",\"DefaultValue\":0},{\"Name\":\"qValues\",\"DefaultValue\":[0]},{\"Name\":\"qToggleMode\",\"DefaultValue\":false}],\"Out\":[{\"Name\":\"qSuccess\"}]},\"SelectHyperCubeCells\":{\"In\":[{\"Name\":\"qPath\",\"DefaultValue\":\"\"},{\"Name\":\"qRowIndices\",\"DefaultValue\":[0]},{\"Name\":\"qColIndices\",\"DefaultValue\":[0]},{\"Name\":\"qSoftLock\",\"DefaultValue\":false,\"Optional\":true},{\"Name\":\"qDeselectOnlyOneSelected\",\"DefaultValue\":false,\"Optional\":true}],\"Out\":[{\"Name\":\"qSuccess\"}]},\"SelectPivotCells\":{\"In\":[{\"Name\":\"qPath\",\"DefaultValue\":\"\"},{\"Name\":\"qSelections\",\"DefaultValue\":[{\"qType\":0,\"qCol\":0,\"qRow\":0}]},{\"Name\":\"qSoftLock\",\"DefaultValue\":false,\"Optional\":true},{\"Name\":\"qDeselectOnlyOneSelected\",\"DefaultValue\":false,\"Optional\":true}],\"Out\":[{\"Name\":\"qSuccess\"}]},\"RangeSelectHyperCubeValues\":{\"In\":[{\"Name\":\"qPath\",\"DefaultValue\":\"\"},{\"Name\":\"qRanges\",\"DefaultValue\":[{\"qRange\":{\"qMin\":0,\"qMax\":0,\"qMinInclEq\":false,\"qMaxInclEq\":false},\"qMeasureIx\":0}]},{\"Name\":\"qColumnsToSelect\",\"DefaultValue\":[0],\"Optional\":true},{\"Name\":\"qOrMode\",\"DefaultValue\":false,\"Optional\":true},{\"Name\":\"qDeselectOnlyOneSelected\",\"DefaultValue\":false,\"Optional\":true}],\"Out\":[{\"Name\":\"qSuccess\"}]},\"MultiRangeSelectHyperCubeValues\":{\"In\":[{\"Name\":\"qPath\",\"DefaultValue\":\"\"},{\"Name\":\"qRanges\",\"DefaultValue\":[{\"qRanges\":[{\"qRange\":{\"qMin\":0,\"qMax\":0,\"qMinInclEq\":false,\"qMaxInclEq\":false},\"qMeasureIx\":0}],\"qColumnsToSelect\":[0]}]},{\"Name\":\"qOrMode\",\"DefaultValue\":false,\"Optional\":true},{\"Name\":\"qDeselectOnlyOneSelected\",\"DefaultValue\":false,\"Optional\":true}],\"Out\":[{\"Name\":\"qSuccess\"}]},\"MultiRangeSelectTreeDataValues\":{\"In\":[{\"Name\":\"qPath\",\"DefaultValue\":\"\"},{\"Name\":\"qRanges\",\"DefaultValue\":[{\"qRanges\":[{\"qRange\":{\"qMin\":0,\"qMax\":0,\"qMinInclEq\":false,\"qMaxInclEq\":false},\"qMeasureIx\":0,\"qDimensionIx\":0}]}]},{\"Name\":\"qOrMode\",\"DefaultValue\":false,\"Optional\":true},{\"Name\":\"qDeselectOnlyOneSelected\",\"DefaultValue\":false,\"Optional\":true}],\"Out\":[{\"Name\":\"qSuccess\"}]},\"SelectHyperCubeContinuousRange\":{\"In\":[{\"Name\":\"qPath\",\"DefaultValue\":\"\"},{\"Name\":\"qRanges\",\"DefaultValue\":[{\"qRange\":{\"qMin\":0,\"qMax\":0,\"qMinInclEq\":false,\"qMaxInclEq\":false},\"qDimIx\":0}]},{\"Name\":\"qSoftLock\",\"DefaultValue\":false,\"Optional\":true}],\"Out\":[{\"Name\":\"qSuccess\"}]},\"GetChild\":{\"In\":[{\"Name\":\"qId\",\"DefaultValue\":\"\"}],\"Out\":[]},\"GetChildInfos\":{\"In\":[],\"Out\":[{\"Name\":\"qInfos\"}]},\"CreateChild\":{\"In\":[{\"Name\":\"qProp\",\"DefaultValue\":{\"qInfo\":{\"qId\":\"\",\"qType\":\"\"},\"qExtendsId\":\"\",\"qMetaDef\":{}}},{\"Name\":\"qPropForThis\",\"DefaultValue\":null,\"Optional\":true}],\"Out\":[{\"Name\":\"qInfo\"}]},\"DestroyChild\":{\"In\":[{\"Name\":\"qId\",\"DefaultValue\":\"\"},{\"Name\":\"qPropForThis\",\"DefaultValue\":null,\"Optional\":true}],\"Out\":[{\"Name\":\"qSuccess\"}]},\"DestroyAllChildren\":{\"In\":[{\"Name\":\"qPropForThis\",\"DefaultValue\":null,\"Optional\":true}],\"Out\":[]},\"SetChildArrayOrder\":{\"In\":[{\"Name\":\"qIds\",\"DefaultValue\":[\"\"]}],\"Out\":[]},\"GetLinkedObjects\":{\"In\":[],\"Out\":[{\"Name\":\"qItems\"}]},\"CopyFrom\":{\"In\":[{\"Name\":\"qFromId\",\"DefaultValue\":\"\"}],\"Out\":[]},\"BeginSelections\":{\"In\":[{\"Name\":\"qPaths\",\"DefaultValue\":[\"\"]}],\"Out\":[]},\"EndSelections\":{\"In\":[{\"Name\":\"qAccept\",\"DefaultValue\":false}],\"Out\":[]},\"ResetMadeSelections\":{\"In\":[],\"Out\":[]},\"EmbedSnapshotObject\":{\"In\":[{\"Name\":\"qId\",\"DefaultValue\":\"\"}],\"Out\":[]},\"GetSnapshotObject\":{\"In\":[],\"Out\":[]},\"Publish\":{\"In\":[],\"Out\":[]},\"UnPublish\":{\"In\":[],\"Out\":[]},\"Approve\":{\"In\":[],\"Out\":[]},\"UnApprove\":{\"In\":[],\"Out\":[]}},\"GenericDimension\":{\"GetLayout\":{\"In\":[],\"Out\":[{\"Name\":\"qLayout\"}]},\"ApplyPatches\":{\"In\":[{\"Name\":\"qPatches\",\"DefaultValue\":[{\"qOp\":0,\"qPath\":\"\",\"qValue\":\"\"}]}],\"Out\":[]},\"SetProperties\":{\"In\":[{\"Name\":\"qProp\",\"DefaultValue\":{\"qInfo\":{\"qId\":\"\",\"qType\":\"\"},\"qDim\":{\"qGrouping\":0,\"qFieldDefs\":[\"\"],\"qFieldLabels\":[\"\"],\"qLabelExpression\":\"\"},\"qMetaDef\":{}}}],\"Out\":[]},\"GetProperties\":{\"In\":[],\"Out\":[{\"Name\":\"qProp\"}]},\"GetInfo\":{\"In\":[],\"Out\":[{\"Name\":\"qInfo\"}]},\"GetDimension\":{\"In\":[],\"Out\":[{\"Name\":\"qDim\"}]},\"GetLinkedObjects\":{\"In\":[],\"Out\":[{\"Name\":\"qItems\"}]},\"Publish\":{\"In\":[],\"Out\":[]},\"UnPublish\":{\"In\":[],\"Out\":[]},\"Approve\":{\"In\":[],\"Out\":[]},\"UnApprove\":{\"In\":[],\"Out\":[]}},\"GenericBookmark\":{\"GetFieldValues\":{\"In\":[{\"Name\":\"qField\",\"DefaultValue\":\"\"},{\"Name\":\"qGetExcludedValues\",\"DefaultValue\":false},{\"Name\":\"qDataPage\",\"DefaultValue\":{\"qStartIndex\":0,\"qEndIndex\":0}}],\"Out\":[{\"Name\":\"qFieldValues\"}]},\"GetLayout\":{\"In\":[],\"Out\":[{\"Name\":\"qLayout\"}]},\"ApplyPatches\":{\"In\":[{\"Name\":\"qPatches\",\"DefaultValue\":[{\"qOp\":0,\"qPath\":\"\",\"qValue\":\"\"}]}],\"Out\":[]},\"SetProperties\":{\"In\":[{\"Name\":\"qProp\",\"DefaultValue\":{\"qInfo\":{\"qId\":\"\",\"qType\":\"\"},\"qMetaDef\":{}}}],\"Out\":[]},\"GetProperties\":{\"In\":[],\"Out\":[{\"Name\":\"qProp\"}]},\"GetInfo\":{\"In\":[],\"Out\":[{\"Name\":\"qInfo\"}]},\"Apply\":{\"In\":[],\"Out\":[{\"Name\":\"qSuccess\"}]},\"Publish\":{\"In\":[],\"Out\":[]},\"UnPublish\":{\"In\":[],\"Out\":[]},\"Approve\":{\"In\":[],\"Out\":[]},\"UnApprove\":{\"In\":[],\"Out\":[]}},\"GenericVariable\":{\"GetLayout\":{\"In\":[],\"Out\":[{\"Name\":\"qLayout\"}]},\"ApplyPatches\":{\"In\":[{\"Name\":\"qPatches\",\"DefaultValue\":[{\"qOp\":0,\"qPath\":\"\",\"qValue\":\"\"}]}],\"Out\":[]},\"SetProperties\":{\"In\":[{\"Name\":\"qProp\",\"DefaultValue\":{\"qInfo\":{\"qId\":\"\",\"qType\":\"\"},\"qMetaDef\":{},\"qName\":\"\",\"qComment\":\"\",\"qNumberPresentation\":{\"qType\":0,\"qnDec\":0,\"qUseThou\":0,\"qFmt\":\"\",\"qDec\":\"\",\"qThou\":\"\"},\"qIncludeInBookmark\":false,\"qDefinition\":\"\"}}],\"Out\":[]},\"GetProperties\":{\"In\":[],\"Out\":[{\"Name\":\"qProp\"}]},\"GetInfo\":{\"In\":[],\"Out\":[{\"Name\":\"qInfo\"}]},\"SetStringValue\":{\"In\":[{\"Name\":\"qVal\",\"DefaultValue\":\"\"}],\"Out\":[]},\"SetNumValue\":{\"In\":[{\"Name\":\"qVal\",\"DefaultValue\":0}],\"Out\":[]},\"SetDualValue\":{\"In\":[{\"Name\":\"qText\",\"DefaultValue\":\"\"},{\"Name\":\"qNum\",\"DefaultValue\":0}],\"Out\":[]}},\"GenericMeasure\":{\"GetLayout\":{\"In\":[],\"Out\":[{\"Name\":\"qLayout\"}]},\"ApplyPatches\":{\"In\":[{\"Name\":\"qPatches\",\"DefaultValue\":[{\"qOp\":0,\"qPath\":\"\",\"qValue\":\"\"}]}],\"Out\":[]},\"SetProperties\":{\"In\":[{\"Name\":\"qProp\",\"DefaultValue\":{\"qInfo\":{\"qId\":\"\",\"qType\":\"\"},\"qMeasure\":{\"qLabel\":\"\",\"qDef\":\"\",\"qGrouping\":0,\"qExpressions\":[\"\"],\"qActiveExpression\":0,\"qLabelExpression\":\"\"},\"qMetaDef\":{}}}],\"Out\":[]},\"GetProperties\":{\"In\":[],\"Out\":[{\"Name\":\"qProp\"}]},\"GetInfo\":{\"In\":[],\"Out\":[{\"Name\":\"qInfo\"}]},\"GetMeasure\":{\"In\":[],\"Out\":[{\"Name\":\"qMeasure\"}]},\"GetLinkedObjects\":{\"In\":[],\"Out\":[{\"Name\":\"qItems\"}]},\"Publish\":{\"In\":[],\"Out\":[]},\"UnPublish\":{\"In\":[],\"Out\":[]},\"Approve\":{\"In\":[],\"Out\":[]},\"UnApprove\":{\"In\":[],\"Out\":[]}},\"Doc\":{\"GetField\":{\"In\":[{\"Name\":\"qFieldName\",\"DefaultValue\":\"\"},{\"Name\":\"qStateName\",\"DefaultValue\":\"\",\"Optional\":true}],\"Out\":[]},\"GetFieldDescription\":{\"In\":[{\"Name\":\"qFieldName\",\"DefaultValue\":\"\"}],\"Out\":[]},\"GetVariable\":{\"In\":[{\"Name\":\"qName\",\"DefaultValue\":\"\"}],\"Out\":[]},\"GetLooselyCoupledVector\":{\"In\":[],\"Out\":[{\"Name\":\"qv\"}]},\"SetLooselyCoupledVector\":{\"In\":[{\"Name\":\"qv\",\"DefaultValue\":[0]}],\"Out\":[]},\"Evaluate\":{\"In\":[{\"Name\":\"qExpression\",\"DefaultValue\":\"\"}],\"Out\":[]},\"EvaluateEx\":{\"In\":[{\"Name\":\"qExpression\",\"DefaultValue\":\"\"}],\"Out\":[{\"Name\":\"qValue\"}]},\"ClearAll\":{\"In\":[{\"Name\":\"qLockedAlso\",\"DefaultValue\":false,\"Optional\":true},{\"Name\":\"qStateName\",\"DefaultValue\":\"\",\"Optional\":true}],\"Out\":[]},\"LockAll\":{\"In\":[{\"Name\":\"qStateName\",\"DefaultValue\":\"\",\"Optional\":true}],\"Out\":[]},\"UnlockAll\":{\"In\":[{\"Name\":\"qStateName\",\"DefaultValue\":\"\",\"Optional\":true}],\"Out\":[]},\"Back\":{\"In\":[],\"Out\":[]},\"Forward\":{\"In\":[],\"Out\":[]},\"CreateVariable\":{\"In\":[{\"Name\":\"qName\",\"DefaultValue\":\"\"}],\"Out\":[]},\"RemoveVariable\":{\"In\":[{\"Name\":\"qName\",\"DefaultValue\":\"\"}],\"Out\":[]},\"GetLocaleInfo\":{\"In\":[],\"Out\":[]},\"GetTablesAndKeys\":{\"In\":[{\"Name\":\"qWindowSize\",\"DefaultValue\":{\"qcx\":0,\"qcy\":0}},{\"Name\":\"qNullSize\",\"DefaultValue\":{\"qcx\":0,\"qcy\":0}},{\"Name\":\"qCellHeight\",\"DefaultValue\":0},{\"Name\":\"qSyntheticMode\",\"DefaultValue\":false},{\"Name\":\"qIncludeSysVars\",\"DefaultValue\":false}],\"Out\":[{\"Name\":\"qtr\"},{\"Name\":\"qk\"}]},\"GetViewDlgSaveInfo\":{\"In\":[],\"Out\":[]},\"SetViewDlgSaveInfo\":{\"In\":[{\"Name\":\"qInfo\",\"DefaultValue\":{\"qPos\":{\"qLeft\":0,\"qTop\":0,\"qWidth\":0,\"qHeight\":0},\"qCtlInfo\":{\"qInternalView\":{\"qTables\":[{\"qPos\":{\"qLeft\":0,\"qTop\":0,\"qWidth\":0,\"qHeight\":0},\"qCaption\":\"\"}],\"qBroomPoints\":[{\"qPos\":{\"qx\":0,\"qy\":0},\"qTable\":\"\",\"qFields\":[\"\"]}],\"qConnectionPoints\":[{\"qPos\":{\"qx\":0,\"qy\":0},\"qFields\":[\"\"]}],\"qZoomFactor\":0},\"qSourceView\":{\"qTables\":[{\"qPos\":{\"qLeft\":0,\"qTop\":0,\"qWidth\":0,\"qHeight\":0},\"qCaption\":\"\"}],\"qBroomPoints\":[{\"qPos\":{\"qx\":0,\"qy\":0},\"qTable\":\"\",\"qFields\":[\"\"]}],\"qConnectionPoints\":[{\"qPos\":{\"qx\":0,\"qy\":0},\"qFields\":[\"\"]}],\"qZoomFactor\":0}},\"qMode\":0}}],\"Out\":[]},\"GetEmptyScript\":{\"In\":[{\"Name\":\"qLocalizedMainSection\",\"DefaultValue\":\"\",\"Optional\":true}],\"Out\":[]},\"DoReload\":{\"In\":[{\"Name\":\"qMode\",\"DefaultValue\":0,\"Optional\":true},{\"Name\":\"qPartial\",\"DefaultValue\":false,\"Optional\":true},{\"Name\":\"qDebug\",\"DefaultValue\":false,\"Optional\":true}],\"Out\":[]},\"GetScriptBreakpoints\":{\"In\":[],\"Out\":[{\"Name\":\"qBreakpoints\"}]},\"SetScriptBreakpoints\":{\"In\":[{\"Name\":\"qBreakpoints\",\"DefaultValue\":[{\"qbufferName\":\"\",\"qlineIx\":0,\"qEnabled\":false}]}],\"Out\":[]},\"GetScript\":{\"In\":[],\"Out\":[{\"Name\":\"qScript\"}]},\"GetTextMacros\":{\"In\":[],\"Out\":[{\"Name\":\"qMacros\"}]},\"SetFetchLimit\":{\"In\":[{\"Name\":\"qLimit\",\"DefaultValue\":0}],\"Out\":[]},\"DoSave\":{\"In\":[{\"Name\":\"qFileName\",\"DefaultValue\":\"\",\"Optional\":true}],\"Out\":[]},\"GetTableData\":{\"In\":[{\"Name\":\"qOffset\",\"DefaultValue\":0},{\"Name\":\"qRows\",\"DefaultValue\":0},{\"Name\":\"qSyntheticMode\",\"DefaultValue\":false},{\"Name\":\"qTableName\",\"DefaultValue\":\"\"}],\"Out\":[{\"Name\":\"qData\"}]},\"GetAppLayout\":{\"In\":[],\"Out\":[{\"Name\":\"qLayout\"}]},\"SetAppProperties\":{\"In\":[{\"Name\":\"qProp\",\"DefaultValue\":{\"qTitle\":\"\",\"qLastReloadTime\":\"\",\"qMigrationHash\":\"\",\"qSavedInProductVersion\":\"\",\"qThumbnail\":{\"qUrl\":\"\"}}}],\"Out\":[]},\"GetAppProperties\":{\"In\":[],\"Out\":[{\"Name\":\"qProp\"}]},\"GetLineage\":{\"In\":[],\"Out\":[{\"Name\":\"qLineage\"}]},\"CreateSessionObject\":{\"In\":[{\"Name\":\"qProp\",\"DefaultValue\":{\"qInfo\":{\"qId\":\"\",\"qType\":\"\"},\"qExtendsId\":\"\",\"qMetaDef\":{}}}],\"Out\":[]},\"DestroySessionObject\":{\"In\":[{\"Name\":\"qId\",\"DefaultValue\":\"\"}],\"Out\":[{\"Name\":\"qSuccess\"}]},\"CreateObject\":{\"In\":[{\"Name\":\"qProp\",\"DefaultValue\":{\"qInfo\":{\"qId\":\"\",\"qType\":\"\"},\"qExtendsId\":\"\",\"qMetaDef\":{}}}],\"Out\":[{\"Name\":\"qInfo\"}]},\"DestroyObject\":{\"In\":[{\"Name\":\"qId\",\"DefaultValue\":\"\"}],\"Out\":[{\"Name\":\"qSuccess\"}]},\"GetObject\":{\"In\":[{\"Name\":\"qId\",\"DefaultValue\":\"\"}],\"Out\":[]},\"GetObjects\":{\"In\":[{\"Name\":\"qOptions\",\"DefaultValue\":{\"qTypes\":[\"\"],\"qIncludeSessionObjects\":false,\"qData\":{}}}],\"Out\":[{\"Name\":\"qList\"}]},\"GetBookmarks\":{\"In\":[{\"Name\":\"qOptions\",\"DefaultValue\":{\"qTypes\":[\"\"],\"qData\":{}}}],\"Out\":[{\"Name\":\"qList\"}]},\"CloneObject\":{\"In\":[{\"Name\":\"qId\",\"DefaultValue\":\"\"}],\"Out\":[{\"Name\":\"qCloneId\"}]},\"CreateDraft\":{\"In\":[{\"Name\":\"qId\",\"DefaultValue\":\"\"}],\"Out\":[{\"Name\":\"qDraftId\"}]},\"CommitDraft\":{\"In\":[{\"Name\":\"qId\",\"DefaultValue\":\"\"}],\"Out\":[]},\"DestroyDraft\":{\"In\":[{\"Name\":\"qId\",\"DefaultValue\":\"\"},{\"Name\":\"qSourceId\",\"DefaultValue\":\"\"}],\"Out\":[{\"Name\":\"qSuccess\"}]},\"Undo\":{\"In\":[],\"Out\":[{\"Name\":\"qSuccess\"}]},\"Redo\":{\"In\":[],\"Out\":[{\"Name\":\"qSuccess\"}]},\"ClearUndoBuffer\":{\"In\":[],\"Out\":[]},\"CreateDimension\":{\"In\":[{\"Name\":\"qProp\",\"DefaultValue\":{\"qInfo\":{\"qId\":\"\",\"qType\":\"\"},\"qDim\":{\"qGrouping\":0,\"qFieldDefs\":[\"\"],\"qFieldLabels\":[\"\"],\"qLabelExpression\":\"\"},\"qMetaDef\":{}}}],\"Out\":[{\"Name\":\"qInfo\"}]},\"DestroyDimension\":{\"In\":[{\"Name\":\"qId\",\"DefaultValue\":\"\"}],\"Out\":[{\"Name\":\"qSuccess\"}]},\"GetDimension\":{\"In\":[{\"Name\":\"qId\",\"DefaultValue\":\"\"}],\"Out\":[]},\"CloneDimension\":{\"In\":[{\"Name\":\"qId\",\"DefaultValue\":\"\"}],\"Out\":[{\"Name\":\"qCloneId\"}]},\"CreateMeasure\":{\"In\":[{\"Name\":\"qProp\",\"DefaultValue\":{\"qInfo\":{\"qId\":\"\",\"qType\":\"\"},\"qMeasure\":{\"qLabel\":\"\",\"qDef\":\"\",\"qGrouping\":0,\"qExpressions\":[\"\"],\"qActiveExpression\":0,\"qLabelExpression\":\"\"},\"qMetaDef\":{}}}],\"Out\":[{\"Name\":\"qInfo\"}]},\"DestroyMeasure\":{\"In\":[{\"Name\":\"qId\",\"DefaultValue\":\"\"}],\"Out\":[{\"Name\":\"qSuccess\"}]},\"GetMeasure\":{\"In\":[{\"Name\":\"qId\",\"DefaultValue\":\"\"}],\"Out\":[]},\"CloneMeasure\":{\"In\":[{\"Name\":\"qId\",\"DefaultValue\":\"\"}],\"Out\":[{\"Name\":\"qCloneId\"}]},\"CreateSessionVariable\":{\"In\":[{\"Name\":\"qProp\",\"DefaultValue\":{\"qInfo\":{\"qId\":\"\",\"qType\":\"\"},\"qMetaDef\":{},\"qName\":\"\",\"qComment\":\"\",\"qNumberPresentation\":{\"qType\":0,\"qnDec\":0,\"qUseThou\":0,\"qFmt\":\"\",\"qDec\":\"\",\"qThou\":\"\"},\"qIncludeInBookmark\":false,\"qDefinition\":\"\"}}],\"Out\":[]},\"DestroySessionVariable\":{\"In\":[{\"Name\":\"qId\",\"DefaultValue\":\"\"}],\"Out\":[{\"Name\":\"qSuccess\"}]},\"CreateVariableEx\":{\"In\":[{\"Name\":\"qProp\",\"DefaultValue\":{\"qInfo\":{\"qId\":\"\",\"qType\":\"\"},\"qMetaDef\":{},\"qName\":\"\",\"qComment\":\"\",\"qNumberPresentation\":{\"qType\":0,\"qnDec\":0,\"qUseThou\":0,\"qFmt\":\"\",\"qDec\":\"\",\"qThou\":\"\"},\"qIncludeInBookmark\":false,\"qDefinition\":\"\"}}],\"Out\":[{\"Name\":\"qInfo\"}]},\"DestroyVariableById\":{\"In\":[{\"Name\":\"qId\",\"DefaultValue\":\"\"}],\"Out\":[{\"Name\":\"qSuccess\"}]},\"DestroyVariableByName\":{\"In\":[{\"Name\":\"qName\",\"DefaultValue\":\"\"}],\"Out\":[{\"Name\":\"qSuccess\"}]},\"GetVariableById\":{\"In\":[{\"Name\":\"qId\",\"DefaultValue\":\"\"}],\"Out\":[]},\"GetVariableByName\":{\"In\":[{\"Name\":\"qName\",\"DefaultValue\":\"\"}],\"Out\":[]},\"MigrateVariables\":{\"In\":[],\"Out\":[]},\"MigrateDerivedFields\":{\"In\":[],\"Out\":[]},\"CheckExpression\":{\"In\":[{\"Name\":\"qExpr\",\"DefaultValue\":\"\"},{\"Name\":\"qLabels\",\"DefaultValue\":[\"\"],\"Optional\":true}],\"Out\":[{\"Name\":\"qErrorMsg\"},{\"Name\":\"qBadFieldNames\"},{\"Name\":\"qDangerousFieldNames\"}]},\"CheckNumberOrExpression\":{\"In\":[{\"Name\":\"qExpr\",\"DefaultValue\":\"\"}],\"Out\":[{\"Name\":\"qErrorMsg\"},{\"Name\":\"qBadFieldNames\"}]},\"AddAlternateState\":{\"In\":[{\"Name\":\"qStateName\",\"DefaultValue\":\"\"}],\"Out\":[]},\"RemoveAlternateState\":{\"In\":[{\"Name\":\"qStateName\",\"DefaultValue\":\"\"}],\"Out\":[]},\"CreateBookmark\":{\"In\":[{\"Name\":\"qProp\",\"DefaultValue\":{\"qInfo\":{\"qId\":\"\",\"qType\":\"\"},\"qMetaDef\":{}}}],\"Out\":[{\"Name\":\"qInfo\"}]},\"DestroyBookmark\":{\"In\":[{\"Name\":\"qId\",\"DefaultValue\":\"\"}],\"Out\":[{\"Name\":\"qSuccess\"}]},\"GetBookmark\":{\"In\":[{\"Name\":\"qId\",\"DefaultValue\":\"\"}],\"Out\":[]},\"ApplyBookmark\":{\"In\":[{\"Name\":\"qId\",\"DefaultValue\":\"\"}],\"Out\":[{\"Name\":\"qSuccess\"}]},\"CloneBookmark\":{\"In\":[{\"Name\":\"qId\",\"DefaultValue\":\"\"}],\"Out\":[{\"Name\":\"qCloneId\"}]},\"AddFieldFromExpression\":{\"In\":[{\"Name\":\"qName\",\"DefaultValue\":\"\"},{\"Name\":\"qExpr\",\"DefaultValue\":\"\"}],\"Out\":[{\"Name\":\"qSuccess\"}]},\"GetFieldOnTheFlyByName\":{\"In\":[{\"Name\":\"qReadableName\",\"DefaultValue\":\"\"}],\"Out\":[{\"Name\":\"qName\"}]},\"GetAllInfos\":{\"In\":[],\"Out\":[{\"Name\":\"qInfos\"}]},\"Resume\":{\"In\":[],\"Out\":[]},\"AbortModal\":{\"In\":[{\"Name\":\"qAccept\",\"DefaultValue\":false}],\"Out\":[]},\"Publish\":{\"In\":[{\"Name\":\"qStreamId\",\"DefaultValue\":\"\"},{\"Name\":\"qName\",\"DefaultValue\":\"\",\"Optional\":true}],\"Out\":[]},\"UnPublish\":{\"In\":[],\"Out\":[]},\"GetMatchingFields\":{\"In\":[{\"Name\":\"qTags\",\"DefaultValue\":[\"\"]},{\"Name\":\"qMatchingFieldMode\",\"DefaultValue\":0,\"Optional\":true}],\"Out\":[{\"Name\":\"qFieldNames\"}]},\"FindMatchingFields\":{\"In\":[{\"Name\":\"qFieldName\",\"DefaultValue\":\"\"},{\"Name\":\"qTags\",\"DefaultValue\":[\"\"]}],\"Out\":[{\"Name\":\"qFieldNames\"}]},\"Scramble\":{\"In\":[{\"Name\":\"qFieldName\",\"DefaultValue\":\"\"}],\"Out\":[]},\"SaveObjects\":{\"In\":[],\"Out\":[]},\"GetAssociationScores\":{\"In\":[{\"Name\":\"qTable1\",\"DefaultValue\":\"\"},{\"Name\":\"qTable2\",\"DefaultValue\":\"\"}],\"Out\":[{\"Name\":\"qScore\"}]},\"GetMediaList\":{\"In\":[],\"Out\":[{\"Name\":\"qList\"}]},\"GetContentLibraries\":{\"In\":[],\"Out\":[{\"Name\":\"qList\"}]},\"GetLibraryContent\":{\"In\":[{\"Name\":\"qName\",\"DefaultValue\":\"\"}],\"Out\":[{\"Name\":\"qList\"}]},\"DoReloadEx\":{\"In\":[{\"Name\":\"qParams\",\"DefaultValue\":{\"qMode\":0,\"qPartial\":false,\"qDebug\":false},\"Optional\":true}],\"Out\":[{\"Name\":\"qResult\"}]},\"BackCount\":{\"In\":[],\"Out\":[]},\"ForwardCount\":{\"In\":[],\"Out\":[]},\"ExportReducedData\":{\"In\":[{\"Name\":\"qOptions\",\"DefaultValue\":{\"qBookmarkId\":\"\",\"qExpires\":0},\"Optional\":true}],\"Out\":[{\"Name\":\"qDownloadInfo\"}]},\"SetScript\":{\"In\":[{\"Name\":\"qScript\",\"DefaultValue\":\"\"}],\"Out\":[]},\"CheckScriptSyntax\":{\"In\":[],\"Out\":[{\"Name\":\"qErrors\"}]},\"GetFavoriteVariables\":{\"In\":[],\"Out\":[{\"Name\":\"qNames\"}]},\"SetFavoriteVariables\":{\"In\":[{\"Name\":\"qNames\",\"DefaultValue\":[\"\"]}],\"Out\":[]},\"GetIncludeFileContent\":{\"In\":[{\"Name\":\"qPath\",\"DefaultValue\":\"\"}],\"Out\":[{\"Name\":\"qContent\"}]},\"CreateConnection\":{\"In\":[{\"Name\":\"qConnection\",\"DefaultValue\":{\"qId\":\"\",\"qName\":\"\",\"qConnectionString\":\"\",\"qType\":\"\",\"qUserName\":\"\",\"qPassword\":\"\",\"qModifiedDate\":\"\",\"qMeta\":{\"qName\":\"\"},\"qLogOn\":0}}],\"Out\":[{\"Name\":\"qConnectionId\"}]},\"ModifyConnection\":{\"In\":[{\"Name\":\"qConnectionId\",\"DefaultValue\":\"\"},{\"Name\":\"qConnection\",\"DefaultValue\":{\"qId\":\"\",\"qName\":\"\",\"qConnectionString\":\"\",\"qType\":\"\",\"qUserName\":\"\",\"qPassword\":\"\",\"qModifiedDate\":\"\",\"qMeta\":{\"qName\":\"\"},\"qLogOn\":0}},{\"Name\":\"qOverrideCredentials\",\"DefaultValue\":false,\"Optional\":true}],\"Out\":[]},\"DeleteConnection\":{\"In\":[{\"Name\":\"qConnectionId\",\"DefaultValue\":\"\"}],\"Out\":[]},\"GetConnection\":{\"In\":[{\"Name\":\"qConnectionId\",\"DefaultValue\":\"\"}],\"Out\":[{\"Name\":\"qConnection\"}]},\"GetConnections\":{\"In\":[],\"Out\":[{\"Name\":\"qConnections\"}]},\"GetDatabaseInfo\":{\"In\":[{\"Name\":\"qConnectionId\",\"DefaultValue\":\"\"}],\"Out\":[{\"Name\":\"qInfo\"}]},\"GetDatabases\":{\"In\":[{\"Name\":\"qConnectionId\",\"DefaultValue\":\"\"}],\"Out\":[{\"Name\":\"qDatabases\"}]},\"GetDatabaseOwners\":{\"In\":[{\"Name\":\"qConnectionId\",\"DefaultValue\":\"\"},{\"Name\":\"qDatabase\",\"DefaultValue\":\"\",\"Optional\":true}],\"Out\":[{\"Name\":\"qOwners\"}]},\"GetDatabaseTables\":{\"In\":[{\"Name\":\"qConnectionId\",\"DefaultValue\":\"\"},{\"Name\":\"qDatabase\",\"DefaultValue\":\"\",\"Optional\":true},{\"Name\":\"qOwner\",\"DefaultValue\":\"\",\"Optional\":true}],\"Out\":[{\"Name\":\"qTables\"}]},\"GetDatabaseTableFields\":{\"In\":[{\"Name\":\"qConnectionId\",\"DefaultValue\":\"\"},{\"Name\":\"qDatabase\",\"DefaultValue\":\"\",\"Optional\":true},{\"Name\":\"qOwner\",\"DefaultValue\":\"\",\"Optional\":true},{\"Name\":\"qTable\",\"DefaultValue\":\"\"}],\"Out\":[{\"Name\":\"qFields\"}]},\"GetDatabaseTablePreview\":{\"In\":[{\"Name\":\"qConnectionId\",\"DefaultValue\":\"\"},{\"Name\":\"qDatabase\",\"DefaultValue\":\"\",\"Optional\":true},{\"Name\":\"qOwner\",\"DefaultValue\":\"\",\"Optional\":true},{\"Name\":\"qTable\",\"DefaultValue\":\"\"},{\"Name\":\"qConditions\",\"DefaultValue\":{\"qType\":0,\"qWherePredicate\":\"\"},\"Optional\":true}],\"Out\":[{\"Name\":\"qPreview\"},{\"Name\":\"qRowCount\"}]},\"GetFolderItemsForConnection\":{\"In\":[{\"Name\":\"qConnectionId\",\"DefaultValue\":\"\"},{\"Name\":\"qRelativePath\",\"DefaultValue\":\"\",\"Optional\":true}],\"Out\":[{\"Name\":\"qFolderItems\"}]},\"GuessFileType\":{\"In\":[{\"Name\":\"qConnectionId\",\"DefaultValue\":\"\"},{\"Name\":\"qRelativePath\",\"DefaultValue\":\"\",\"Optional\":true}],\"Out\":[{\"Name\":\"qDataFormat\"}]},\"GetFileTables\":{\"In\":[{\"Name\":\"qConnectionId\",\"DefaultValue\":\"\"},{\"Name\":\"qRelativePath\",\"DefaultValue\":\"\",\"Optional\":true},{\"Name\":\"qDataFormat\",\"DefaultValue\":{\"qType\":0,\"qLabel\":\"\",\"qQuote\":\"\",\"qComment\":\"\",\"qDelimiter\":{\"qName\":\"\",\"qScriptCode\":\"\",\"qNumber\":0,\"qIsMultiple\":false},\"qCodePage\":0,\"qHeaderSize\":0,\"qRecordSize\":0,\"qTabSize\":0,\"qIgnoreEOF\":false,\"qFixedWidthDelimiters\":\"\"}}],\"Out\":[{\"Name\":\"qTables\"}]},\"GetFileTableFields\":{\"In\":[{\"Name\":\"qConnectionId\",\"DefaultValue\":\"\"},{\"Name\":\"qRelativePath\",\"DefaultValue\":\"\",\"Optional\":true},{\"Name\":\"qDataFormat\",\"DefaultValue\":{\"qType\":0,\"qLabel\":\"\",\"qQuote\":\"\",\"qComment\":\"\",\"qDelimiter\":{\"qName\":\"\",\"qScriptCode\":\"\",\"qNumber\":0,\"qIsMultiple\":false},\"qCodePage\":0,\"qHeaderSize\":0,\"qRecordSize\":0,\"qTabSize\":0,\"qIgnoreEOF\":false,\"qFixedWidthDelimiters\":\"\"}},{\"Name\":\"qTable\",\"DefaultValue\":\"\"}],\"Out\":[{\"Name\":\"qFields\"},{\"Name\":\"qFormatSpec\"}]},\"GetFileTablePreview\":{\"In\":[{\"Name\":\"qConnectionId\",\"DefaultValue\":\"\"},{\"Name\":\"qRelativePath\",\"DefaultValue\":\"\",\"Optional\":true},{\"Name\":\"qDataFormat\",\"DefaultValue\":{\"qType\":0,\"qLabel\":\"\",\"qQuote\":\"\",\"qComment\":\"\",\"qDelimiter\":{\"qName\":\"\",\"qScriptCode\":\"\",\"qNumber\":0,\"qIsMultiple\":false},\"qCodePage\":0,\"qHeaderSize\":0,\"qRecordSize\":0,\"qTabSize\":0,\"qIgnoreEOF\":false,\"qFixedWidthDelimiters\":\"\"}},{\"Name\":\"qTable\",\"DefaultValue\":\"\"}],\"Out\":[{\"Name\":\"qPreview\"},{\"Name\":\"qFormatSpec\"}]},\"GetFileTablesEx\":{\"In\":[{\"Name\":\"qConnectionId\",\"DefaultValue\":\"\"},{\"Name\":\"qRelativePath\",\"DefaultValue\":\"\",\"Optional\":true},{\"Name\":\"qDataFormat\",\"DefaultValue\":{\"qType\":0,\"qLabel\":\"\",\"qQuote\":\"\",\"qComment\":\"\",\"qDelimiter\":{\"qName\":\"\",\"qScriptCode\":\"\",\"qNumber\":0,\"qIsMultiple\":false},\"qCodePage\":0,\"qHeaderSize\":0,\"qRecordSize\":0,\"qTabSize\":0,\"qIgnoreEOF\":false,\"qFixedWidthDelimiters\":\"\"}}],\"Out\":[{\"Name\":\"qTables\"}]},\"SendGenericCommandToCustomConnector\":{\"In\":[{\"Name\":\"qProvider\",\"DefaultValue\":\"\"},{\"Name\":\"qCommand\",\"DefaultValue\":\"\"},{\"Name\":\"qMethod\",\"DefaultValue\":\"\"},{\"Name\":\"qParameters\",\"DefaultValue\":[\"\"]},{\"Name\":\"qAppendConnection\",\"DefaultValue\":\"\"}],\"Out\":[{\"Name\":\"qResult\"}]},\"SearchSuggest\":{\"In\":[{\"Name\":\"qOptions\",\"DefaultValue\":{\"qSearchFields\":[\"\"],\"qContext\":0,\"qCharEncoding\":0,\"qAttributes\":[\"\"]}},{\"Name\":\"qTerms\",\"DefaultValue\":[\"\"]}],\"Out\":[{\"Name\":\"qResult\"}]},\"SearchAssociations\":{\"In\":[{\"Name\":\"qOptions\",\"DefaultValue\":{\"qSearchFields\":[\"\"],\"qContext\":0,\"qCharEncoding\":0,\"qAttributes\":[\"\"]}},{\"Name\":\"qTerms\",\"DefaultValue\":[\"\"]},{\"Name\":\"qPage\",\"DefaultValue\":{\"qOffset\":0,\"qCount\":0,\"qMaxNbrFieldMatches\":0,\"qGroupOptions\":[{\"qGroupType\":0,\"qOffset\":0,\"qCount\":0}],\"qGroupItemOptions\":[{\"qGroupItemType\":0,\"qOffset\":0,\"qCount\":0}]}}],\"Out\":[{\"Name\":\"qResults\"}]},\"SelectAssociations\":{\"In\":[{\"Name\":\"qOptions\",\"DefaultValue\":{\"qSearchFields\":[\"\"],\"qContext\":0,\"qCharEncoding\":0,\"qAttributes\":[\"\"]}},{\"Name\":\"qTerms\",\"DefaultValue\":[\"\"]},{\"Name\":\"qMatchIx\",\"DefaultValue\":0},{\"Name\":\"qSoftLock\",\"DefaultValue\":null,\"Optional\":true}],\"Out\":[]},\"SearchResults\":{\"In\":[{\"Name\":\"qOptions\",\"DefaultValue\":{\"qSearchFields\":[\"\"],\"qContext\":0,\"qCharEncoding\":0,\"qAttributes\":[\"\"]}},{\"Name\":\"qTerms\",\"DefaultValue\":[\"\"]},{\"Name\":\"qPage\",\"DefaultValue\":{\"qOffset\":0,\"qCount\":0,\"qMaxNbrFieldMatches\":0,\"qGroupOptions\":[{\"qGroupType\":0,\"qOffset\":0,\"qCount\":0}],\"qGroupItemOptions\":[{\"qGroupItemType\":0,\"qOffset\":0,\"qCount\":0}]}}],\"Out\":[{\"Name\":\"qResult\"}]},\"SearchObjects\":{\"In\":[{\"Name\":\"qOptions\",\"DefaultValue\":{\"qAttributes\":[\"\"],\"qCharEncoding\":0}},{\"Name\":\"qTerms\",\"DefaultValue\":[\"\"]},{\"Name\":\"qPage\",\"DefaultValue\":{\"qOffset\":0,\"qCount\":0,\"qMaxNbrFieldMatches\":0,\"qGroupOptions\":[{\"qGroupType\":0,\"qOffset\":0,\"qCount\":0}],\"qGroupItemOptions\":[{\"qGroupItemType\":0,\"qOffset\":0,\"qCount\":0}]}}],\"Out\":[{\"Name\":\"qResult\"}]},\"GetScriptEx\":{\"In\":[],\"Out\":[{\"Name\":\"qScript\"}]}},\"Global\":{\"AbortRequest\":{\"In\":[{\"Name\":\"qRequestId\",\"DefaultValue\":0}],\"Out\":[]},\"AbortAll\":{\"In\":[],\"Out\":[]},\"GetProgress\":{\"In\":[{\"Name\":\"qRequestId\",\"DefaultValue\":0}],\"Out\":[{\"Name\":\"qProgressData\"}]},\"QvVersion\":{\"In\":[],\"Out\":[]},\"OSVersion\":{\"In\":[],\"Out\":[]},\"OSName\":{\"In\":[],\"Out\":[]},\"QTProduct\":{\"In\":[],\"Out\":[]},\"GetDocList\":{\"In\":[],\"Out\":[{\"Name\":\"qDocList\"}]},\"GetInteract\":{\"In\":[{\"Name\":\"qRequestId\",\"DefaultValue\":0}],\"Out\":[{\"Name\":\"qDef\"}]},\"InteractDone\":{\"In\":[{\"Name\":\"qRequestId\",\"DefaultValue\":0},{\"Name\":\"qDef\",\"DefaultValue\":{\"qType\":0,\"qTitle\":\"\",\"qMsg\":\"\",\"qButtons\":0,\"qLine\":\"\",\"qOldLineNr\":0,\"qNewLineNr\":0,\"qPath\":\"\",\"qHidden\":false,\"qResult\":0,\"qInput\":\"\"}}],\"Out\":[]},\"GetAuthenticatedUser\":{\"In\":[],\"Out\":[]},\"CreateDocEx\":{\"In\":[{\"Name\":\"qDocName\",\"DefaultValue\":\"\"},{\"Name\":\"qUserName\",\"DefaultValue\":\"\",\"Optional\":true},{\"Name\":\"qPassword\",\"DefaultValue\":\"\",\"Optional\":true},{\"Name\":\"qSerial\",\"DefaultValue\":\"\",\"Optional\":true},{\"Name\":\"qLocalizedScriptMainSection\",\"DefaultValue\":\"\",\"Optional\":true}],\"Out\":[{\"Name\":\"qDocId\"}]},\"GetActiveDoc\":{\"In\":[],\"Out\":[]},\"AllowCreateApp\":{\"In\":[],\"Out\":[]},\"CreateApp\":{\"In\":[{\"Name\":\"qAppName\",\"DefaultValue\":\"\"},{\"Name\":\"qLocalizedScriptMainSection\",\"DefaultValue\":\"\",\"Optional\":true}],\"Out\":[{\"Name\":\"qSuccess\"},{\"Name\":\"qAppId\"}]},\"DeleteApp\":{\"In\":[{\"Name\":\"qAppId\",\"DefaultValue\":\"\"}],\"Out\":[{\"Name\":\"qSuccess\"}]},\"IsDesktopMode\":{\"In\":[],\"Out\":[]},\"GetConfiguration\":{\"In\":[],\"Out\":[{\"Name\":\"qConfig\"}]},\"CancelRequest\":{\"In\":[{\"Name\":\"qRequestId\",\"DefaultValue\":0}],\"Out\":[]},\"ShutdownProcess\":{\"In\":[],\"Out\":[]},\"ReloadExtensionList\":{\"In\":[],\"Out\":[]},\"ReplaceAppFromID\":{\"In\":[{\"Name\":\"qTargetAppId\",\"DefaultValue\":\"\"},{\"Name\":\"qSrcAppID\",\"DefaultValue\":\"\"},{\"Name\":\"qIds\",\"DefaultValue\":[\"\"]}],\"Out\":[{\"Name\":\"qSuccess\"}]},\"ReplaceAppFromPath\":{\"In\":[{\"Name\":\"qTargetAppId\",\"DefaultValue\":\"\"},{\"Name\":\"qSrcPath\",\"DefaultValue\":\"\"},{\"Name\":\"qIds\",\"DefaultValue\":[\"\"]},{\"Name\":\"qNoData\",\"DefaultValue\":false}],\"Out\":[]},\"CopyApp\":{\"In\":[{\"Name\":\"qTargetAppId\",\"DefaultValue\":\"\"},{\"Name\":\"qSrcAppId\",\"DefaultValue\":\"\"},{\"Name\":\"qIds\",\"DefaultValue\":[\"\"]}],\"Out\":[{\"Name\":\"qSuccess\"}]},\"ImportApp\":{\"In\":[{\"Name\":\"qAppId\",\"DefaultValue\":\"\"},{\"Name\":\"qSrcPath\",\"DefaultValue\":\"\"},{\"Name\":\"qIds\",\"DefaultValue\":[\"\"]}],\"Out\":[{\"Name\":\"qSuccess\"}]},\"ImportAppEx\":{\"In\":[{\"Name\":\"qAppId\",\"DefaultValue\":\"\"},{\"Name\":\"qSrcPath\",\"DefaultValue\":\"\"},{\"Name\":\"qIds\",\"DefaultValue\":[\"\"]},{\"Name\":\"qExcludeConnections\",\"DefaultValue\":false}],\"Out\":[]},\"ExportApp\":{\"In\":[{\"Name\":\"qTargetPath\",\"DefaultValue\":\"\"},{\"Name\":\"qSrcAppId\",\"DefaultValue\":\"\"},{\"Name\":\"qIds\",\"DefaultValue\":[\"\"]},{\"Name\":\"qNoData\",\"DefaultValue\":false,\"Optional\":true}],\"Out\":[{\"Name\":\"qSuccess\"}]},\"PublishApp\":{\"In\":[{\"Name\":\"qAppId\",\"DefaultValue\":\"\"},{\"Name\":\"qName\",\"DefaultValue\":\"\"},{\"Name\":\"qStreamId\",\"DefaultValue\":\"\"}],\"Out\":[]},\"IsPersonalMode\":{\"In\":[],\"Out\":[]},\"GetUniqueID\":{\"In\":[],\"Out\":[{\"Name\":\"qUniqueID\"}]},\"OpenDoc\":{\"In\":[{\"Name\":\"qDocName\",\"DefaultValue\":\"\"},{\"Name\":\"qUserName\",\"DefaultValue\":\"\",\"Optional\":true},{\"Name\":\"qPassword\",\"DefaultValue\":\"\",\"Optional\":true},{\"Name\":\"qSerial\",\"DefaultValue\":\"\",\"Optional\":true},{\"Name\":\"qNoData\",\"DefaultValue\":false,\"Optional\":true}],\"Out\":[]},\"CreateSessionApp\":{\"In\":[],\"Out\":[{\"Name\":\"qSessionAppId\"}]},\"CreateSessionAppFromApp\":{\"In\":[{\"Name\":\"qSrcAppId\",\"DefaultValue\":\"\"}],\"Out\":[{\"Name\":\"qSessionAppId\"}]},\"ProductVersion\":{\"In\":[],\"Out\":[]},\"GetAppEntry\":{\"In\":[{\"Name\":\"qAppID\",\"DefaultValue\":\"\"}],\"Out\":[{\"Name\":\"qEntry\"}]},\"ConfigureReload\":{\"In\":[{\"Name\":\"qCancelOnScriptError\",\"DefaultValue\":false},{\"Name\":\"qUseErrorData\",\"DefaultValue\":false},{\"Name\":\"qInteractOnError\",\"DefaultValue\":false}],\"Out\":[]},\"CancelReload\":{\"In\":[],\"Out\":[]},\"GetBNF\":{\"In\":[{\"Name\":\"qBnfType\",\"DefaultValue\":0}],\"Out\":[{\"Name\":\"qBnfDefs\"}]},\"GetFunctions\":{\"In\":[{\"Name\":\"qGroup\",\"DefaultValue\":0,\"Optional\":true}],\"Out\":[{\"Name\":\"qFunctions\"}]},\"GetOdbcDsns\":{\"In\":[],\"Out\":[{\"Name\":\"qOdbcDsns\"}]},\"GetOleDbProviders\":{\"In\":[],\"Out\":[{\"Name\":\"qOleDbProviders\"}]},\"GetDatabasesFromConnectionString\":{\"In\":[{\"Name\":\"qConnection\",\"DefaultValue\":{\"qId\":\"\",\"qName\":\"\",\"qConnectionString\":\"\",\"qType\":\"\",\"qUserName\":\"\",\"qPassword\":\"\",\"qModifiedDate\":\"\",\"qMeta\":{\"qName\":\"\"},\"qLogOn\":0}}],\"Out\":[{\"Name\":\"qDatabases\"}]},\"IsValidConnectionString\":{\"In\":[{\"Name\":\"qConnection\",\"DefaultValue\":{\"qId\":\"\",\"qName\":\"\",\"qConnectionString\":\"\",\"qType\":\"\",\"qUserName\":\"\",\"qPassword\":\"\",\"qModifiedDate\":\"\",\"qMeta\":{\"qName\":\"\"},\"qLogOn\":0}}],\"Out\":[]},\"GetDefaultAppFolder\":{\"In\":[],\"Out\":[{\"Name\":\"qPath\"}]},\"GetMyDocumentsFolder\":{\"In\":[],\"Out\":[{\"Name\":\"qFolder\"}]},\"GetLogicalDriveStrings\":{\"In\":[],\"Out\":[{\"Name\":\"qDrives\"}]},\"GetFolderItemsForPath\":{\"In\":[{\"Name\":\"qPath\",\"DefaultValue\":\"\"}],\"Out\":[{\"Name\":\"qFolderItems\"}]},\"GetSupportedCodePages\":{\"In\":[],\"Out\":[{\"Name\":\"qCodePages\"}]},\"GetCustomConnectors\":{\"In\":[{\"Name\":\"qReloadList\",\"DefaultValue\":false,\"Optional\":true}],\"Out\":[{\"Name\":\"qConnectors\"}]},\"GetStreamList\":{\"In\":[],\"Out\":[{\"Name\":\"qStreamList\"}]},\"EngineVersion\":{\"In\":[],\"Out\":[{\"Name\":\"qVersion\"}]},\"GetBaseBNF\":{\"In\":[{\"Name\":\"qBnfType\",\"DefaultValue\":0}],\"Out\":[{\"Name\":\"qBnfDefs\"},{\"Name\":\"qBnfHash\"}]},\"GetBaseBNFHash\":{\"In\":[{\"Name\":\"qBnfType\",\"DefaultValue\":0}],\"Out\":[{\"Name\":\"qBnfHash\"}]},\"GetBaseBNFString\":{\"In\":[{\"Name\":\"qBnfType\",\"DefaultValue\":0}],\"Out\":[{\"Name\":\"qBnfStr\"},{\"Name\":\"qBnfHash\"}]}}},\"enums\":{\"LocalizedMessageCode\":{\"LOCMSG_SCRIPTEDITOR_EMPTY_MESSAGE\":0,\"LOCMSG_SCRIPTEDITOR_PROGRESS_SAVING_STARTED\":1,\"LOCMSG_SCRIPTEDITOR_PROGRESS_BYTES_LEFT\":2,\"LOCMSG_SCRIPTEDITOR_PROGRESS_STORING_TABLES\":3,\"LOCMSG_SCRIPTEDITOR_PROGRESS_QVD_ROWS_SO_FAR\":4,\"LOCMSG_SCRIPTEDITOR_PROGRESS_CONNECTED\":5,\"LOCMSG_SCRIPTEDITOR_PROGRESS_CONNECTING_TO\":6,\"LOCMSG_SCRIPTEDITOR_PROGRESS_CONNECT_FAILED\":7,\"LOCMSG_SCRIPTEDITOR_PROGRESS_QVD_ROWISH\":8,\"LOCMSG_SCRIPTEDITOR_PROGRESS_QVD_COLUMNAR\":9,\"LOCMSG_SCRIPTEDITOR_ERROR\":10,\"LOCMSG_SCRIPTEDITOR_DONE\":11,\"LOCMSG_SCRIPTEDITOR_LOAD_EXTERNAL_DATA\":12,\"LOCMSG_SCRIPTEDITOR_PROGRESS_OLD_QVD_ISLOADING\":13,\"LOCMSG_SCRIPTEDITOR_PROGRESS_QVC_LOADING\":14,\"LOCMSG_SCRIPTEDITOR_PROGRESS_QVD_BUFFERED\":15,\"LOCMSG_SCRIPTEDITOR_PROGRESS_QVC_PREPARING\":16,\"LOCMSG_SCRIPTEDITOR_PROGRESS_QVC_APPENDING\":17,\"LOCMSG_SCRIPTEDITOR_REMOVE_SYNTHETIC\":18,\"LOCMSG_SCRIPTEDITOR_PENDING_LINKEDTABLE_FETCHING\":19,\"LOCMSG_SCRIPTEDITOR_RELOAD\":20,\"LOCMSG_SCRIPTEDITOR_LINES_FETCHED\":21,\"LOCMSG_SCRIPTEDITOR_SEARCHINDEX_START\":22,\"LOCMSG_SCRIPTEDITOR_SEARCHINDEX_FIELD\":23,\"LOCMSG_SCRIPTEDITOR_SEARCHINDEX_SUCCESS\":24,\"LOCMSG_SCRIPTEDITOR_SEARCHINDEX_FAILURE\":25,\"LOCMSG_SCRIPTEDITOR_SEARCHINDEX_STARTABORT\":26,\"LOCMSG_SCRIPTEDITOR_SEARCHINDEX_ENDABORT\":27,\"LOCMSG_SCRIPTEDITOR_SEARCHINDEX_TIMEOUT\":28,\"LOCMSG_SCRIPTEDITOR_SEARCHINDEX_OUTOFMEMORY\":29},\"LocalizedErrorCode\":{\"LOCERR_INTERNAL_ERROR\":-128,\"LOCERR_GENERIC_UNKNOWN\":-1,\"LOCERR_GENERIC_OK\":0,\"LOCERR_GENERIC_NOT_SET\":1,\"LOCERR_GENERIC_NOT_FOUND\":2,\"LOCERR_GENERIC_ALREADY_EXISTS\":3,\"LOCERR_GENERIC_INVALID_PATH\":4,\"LOCERR_GENERIC_ACCESS_DENIED\":5,\"LOCERR_GENERIC_OUT_OF_MEMORY\":6,\"LOCERR_GENERIC_NOT_INITIALIZED\":7,\"LOCERR_GENERIC_INVALID_PARAMETERS\":8,\"LOCERR_GENERIC_EMPTY_PARAMETERS\":9,\"LOCERR_GENERIC_INTERNAL_ERROR\":10,\"LOCERR_GENERIC_CORRUPT_DATA\":11,\"LOCERR_GENERIC_MEMORY_INCONSISTENCY\":12,\"LOCERR_GENERIC_INVISIBLE_OWNER_ABORT\":13,\"LOCERR_GENERIC_PROHIBIT_VALIDATE\":14,\"LOCERR_GENERIC_ABORTED\":15,\"LOCERR_GENERIC_CONNECTION_LOST\":16,\"LOCERR_GENERIC_UNSUPPORTED_IN_PRODUCT_VERSION\":17,\"LOCERR_GENERIC_REST_CONNECTION_FAILURE\":18,\"LOCERR_GENERIC_MEMORY_LIMIT_REACHED\":19,\"LOCERR_HTTP_400\":400,\"LOCERR_HTTP_401\":401,\"LOCERR_HTTP_402\":402,\"LOCERR_HTTP_403\":403,\"LOCERR_HTTP_404\":404,\"LOCERR_HTTP_405\":405,\"LOCERR_HTTP_406\":406,\"LOCERR_HTTP_407\":407,\"LOCERR_HTTP_408\":408,\"LOCERR_HTTP_409\":409,\"LOCERR_HTTP_410\":410,\"LOCERR_HTTP_411\":411,\"LOCERR_HTTP_412\":412,\"LOCERR_HTTP_413\":413,\"LOCERR_HTTP_414\":414,\"LOCERR_HTTP_415\":415,\"LOCERR_HTTP_416\":416,\"LOCERR_HTTP_417\":417,\"LOCERR_HTTP_422\":422,\"LOCERR_HTTP_429\":429,\"LOCERR_HTTP_500\":500,\"LOCERR_HTTP_501\":501,\"LOCERR_HTTP_502\":502,\"LOCERR_HTTP_503\":503,\"LOCERR_HTTP_504\":504,\"LOCERR_HTTP_505\":505,\"LOCERR_HTTP_509\":509,\"LOCERR_HTTP_COULD_NOT_RESOLVE_HOST\":700,\"LOCERR_APP_ALREADY_EXISTS\":1000,\"LOCERR_APP_INVALID_NAME\":1001,\"LOCERR_APP_ALREADY_OPEN\":1002,\"LOCERR_APP_NOT_FOUND\":1003,\"LOCERR_APP_IMPORT_FAILED\":1004,\"LOCERR_APP_SAVE_FAILED\":1005,\"LOCERR_APP_CREATE_FAILED\":1006,\"LOCERR_APP_INVALID\":1007,\"LOCERR_APP_CONNECT_FAILED\":1008,\"LOCERR_APP_ALREADY_OPEN_IN_DIFFERENT_MODE\":1009,\"LOCERR_APP_MIGRATION_COULD_NOT_CONTACT_MIGRATION_SERVICE\":1010,\"LOCERR_APP_MIGRATION_COULD_NOT_START_MIGRATION\":1011,\"LOCERR_APP_MIGRATION_FAILURE\":1012,\"LOCERR_APP_SCRIPT_MISSING\":1013,\"LOCERR_APP_EXPORT_FAILED\":1014,\"LOCERR_CONNECTION_ALREADY_EXISTS\":2000,\"LOCERR_CONNECTION_NOT_FOUND\":2001,\"LOCERR_CONNECTION_FAILED_TO_LOAD\":2002,\"LOCERR_CONNECTION_FAILED_TO_IMPORT\":2003,\"LOCERR_CONNECTION_NAME_IS_INVALID\":2004,\"LOCERR_CONNECTOR_NO_FILE_STREAMING_SUPPORT\":2300,\"LOCERR_CONNECTOR_FILESIZE_EXCEEDED_BUFFER_SIZE\":2301,\"LOCERR_FILE_ACCESS_DENIED\":3000,\"LOCERR_FILE_NAME_INVALID\":3001,\"LOCERR_FILE_CORRUPT\":3002,\"LOCERR_FILE_NOT_FOUND\":3003,\"LOCERR_FILE_FORMAT_UNSUPPORTED\":3004,\"LOCERR_FILE_OPENED_IN_UNSUPPORTED_MODE\":3005,\"LOCERR_FILE_TABLE_NOT_FOUND\":3006,\"LOCERR_USER_ACCESS_DENIED\":4000,\"LOCERR_USER_IMPERSONATION_FAILED\":4001,\"LOCERR_SERVER_OUT_OF_SESSION_AND_USER_CALS\":5000,\"LOCERR_SERVER_OUT_OF_SESSION_CALS\":5001,\"LOCERR_SERVER_OUT_OF_USAGE_CALS\":5002,\"LOCERR_SERVER_OUT_OF_CALS\":5003,\"LOCERR_SERVER_OUT_OF_NAMED_CALS\":5004,\"LOCERR_SERVER_OFF_DUTY\":5005,\"LOCERR_SERVER_BUSY\":5006,\"LOCERR_SERVER_LICENSE_EXPIRED\":5007,\"LOCERR_SERVER_AJAX_DISABLED\":5008,\"LOCERR_HC_INVALID_OBJECT\":6000,\"LOCERR_HC_RESULT_TOO_LARGE\":6001,\"LOCERR_HC_INVALID_OBJECT_STATE\":6002,\"LOCERR_HC_MODAL_OBJECT_ERROR\":6003,\"LOCERR_CALC_INVALID_DEF\":7000,\"LOCERR_CALC_NOT_IN_LIB\":7001,\"LOCERR_CALC_HEAP_ERROR\":7002,\"LOCERR_CALC_TOO_LARGE\":7003,\"LOCERR_CALC_TIMEOUT\":7004,\"LOCERR_CALC_EVAL_CONDITION_FAILED\":7005,\"LOCERR_CALC_MIXED_LINKED_AGGREGATION\":7006,\"LOCERR_CALC_MISSING_LINKED\":7007,\"LOCERR_CALC_INVALID_COL_SORT\":7008,\"LOCERR_CALC_PAGES_TOO_LARGE\":7009,\"LOCERR_CALC_SEMANTIC_FIELD_NOT_ALLOWED\":7010,\"LOCERR_CALC_VALIDATION_STATE_INVALID\":7011,\"LOCERR_CALC_PIVOT_DIMENSIONS_ALREADY_EXISTS\":7012,\"LOCERR_CALC_MISSING_LINKED_FIELD\":7013,\"LOCERR_CALC_NOT_CALCULATED\":7014,\"LOCERR_LAYOUT_EXTENDS_INVALID_ID\":8000,\"LOCERR_LAYOUT_LINKED_OBJECT_NOT_FOUND\":8001,\"LOCERR_LAYOUT_LINKED_OBJECT_INVALID\":8002,\"LOCERR_PERSISTENCE_WRITE_FAILED\":9000,\"LOCERR_PERSISTENCE_READ_FAILED\":9001,\"LOCERR_PERSISTENCE_DELETE_FAILED\":9002,\"LOCERR_PERSISTENCE_NOT_FOUND\":9003,\"LOCERR_PERSISTENCE_UNSUPPORTED_VERSION\":9004,\"LOCERR_PERSISTENCE_MIGRATION_FAILED_READ_ONLY\":9005,\"LOCERR_PERSISTENCE_MIGRATION_CANCELLED\":9006,\"LOCERR_PERSISTENCE_MIGRATION_BACKUP_FAILED\":9007,\"LOCERR_PERSISTENCE_DISK_FULL\":9008,\"LOCERR_PERSISTENCE_NOT_SUPPORTED_FOR_SESSION_APP\":9009,\"LOCERR_PERSISTENCE_SYNC_SET_CHUNK_INVALID_PARAMETERS\":9510,\"LOCERR_PERSISTENCE_SYNC_GET_CHUNK_INVALID_PARAMETERS\":9511,\"LOCERR_SCRIPT_DATASOURCE_ACCESS_DENIED\":10000,\"LOCERR_RELOAD_IN_PROGRESS\":11000,\"LOCERR_RELOAD_TABLE_X_NOT_FOUND\":11001,\"LOCERR_RELOAD_UNKNOWN_STATEMENT\":11002,\"LOCERR_RELOAD_EXPECTED_SOMETHING_FOUND_UNKNOWN\":11003,\"LOCERR_RELOAD_EXPECTED_NOTHING_FOUND_UNKNOWN\":11004,\"LOCERR_RELOAD_EXPECTED_ONE_OF_1_TOKENS_FOUND_UNKNOWN\":11005,\"LOCERR_RELOAD_EXPECTED_ONE_OF_2_TOKENS_FOUND_UNKNOWN\":11006,\"LOCERR_RELOAD_EXPECTED_ONE_OF_3_TOKENS_FOUND_UNKNOWN\":11007,\"LOCERR_RELOAD_EXPECTED_ONE_OF_4_TOKENS_FOUND_UNKNOWN\":11008,\"LOCERR_RELOAD_EXPECTED_ONE_OF_5_TOKENS_FOUND_UNKNOWN\":11009,\"LOCERR_RELOAD_EXPECTED_ONE_OF_6_TOKENS_FOUND_UNKNOWN\":11010,\"LOCERR_RELOAD_EXPECTED_ONE_OF_7_TOKENS_FOUND_UNKNOWN\":11011,\"LOCERR_RELOAD_EXPECTED_ONE_OF_8_OR_MORE_TOKENS_FOUND_UNKNOWN\":11012,\"LOCERR_RELOAD_FIELD_X_NOT_FOUND\":11013,\"LOCERR_RELOAD_MAPPING_TABLE_X_NOT_FOUND\":11014,\"LOCERR_RELOAD_LIB_CONNECTION_X_NOT_FOUND\":11015,\"LOCERR_RELOAD_NAME_ALREADY_TAKEN\":11016,\"LOCERR_RELOAD_WRONG_FILE_FORMAT_DIF\":11017,\"LOCERR_RELOAD_WRONG_FILE_FORMAT_BIFF\":11018,\"LOCERR_RELOAD_WRONG_FILE_FORMAT_ENCRYPTED\":11019,\"LOCERR_RELOAD_OPEN_FILE_ERROR\":11020,\"LOCERR_RELOAD_AUTO_GENERATE_COUNT\":11021,\"LOCERR_RELOAD_PE_ILLEGAL_PREFIX_COMB\":11022,\"LOCERR_RELOAD_MATCHING_CONTROL_STATEMENT_ERROR\":11023,\"LOCERR_RELOAD_MATCHING_LIBPATH_X_NOT_FOUND\":11024,\"LOCERR_RELOAD_MATCHING_LIBPATH_X_INVALID\":11025,\"LOCERR_RELOAD_MATCHING_LIBPATH_X_OUTSIDE\":11026,\"LOCERR_RELOAD_NO_QUALIFIED_PATH_FOR_FILE\":11027,\"LOCERR_RELOAD_MODE_STATEMENT_ONLY_FOR_LIB_PATHS\":11028,\"LOCERR_RELOAD_INCONSISTENT_USE_OF_SEMANTIC_FIELDS\":11029,\"LOCERR_RELOAD_NO_OPEN_DATABASE\":11030,\"LOCERR_RELOAD_AGGREGATION_REQUIRED_BY_GROUP_BY\":11031,\"LOCERR_RELOAD_CONNECT_MUST_USE_LIB_PREFIX_IN_THIS_MODE\":11032,\"LOCERR_RELOAD_ODBC_CONNECT_FAILED\":11033,\"LOCERR_RELOAD_OLEDB_CONNECT_FAILED\":11034,\"LOCERR_RELOAD_CUSTOM_CONNECT_FAILED\":11035,\"LOCERR_RELOAD_ODBC_READ_FAILED\":11036,\"LOCERR_RELOAD_OLEDB_READ_FAILED\":11037,\"LOCERR_RELOAD_CUSTOM_READ_FAILED\":11038,\"LOCERR_RELOAD_BINARY_LOAD_PROHIBITED\":11039,\"LOCERR_RELOAD_CONNECTOR_START_FAILED\":11040,\"LOCERR_RELOAD_CONNECTOR_NOT_RESPONDING\":11041,\"LOCERR_RELOAD_CONNECTOR_REPLY_ERROR\":11042,\"LOCERR_RELOAD_CONNECTOR_CONNECT_ERROR\":11043,\"LOCERR_RELOAD_CONNECTOR_NOT_FOUND_ERROR\":11044,\"LOCERR_RELOAD_INPUT_FIELD_WITH_DUPLICATE_KEYS\":11045,\"LOCERR_RELOAD_CONCATENATE_LOAD_NO_PREVIOUS_TABLE\":11046,\"LOCERR_PERSONAL_NEW_VERSION_AVAILABLE\":12000,\"LOCERR_PERSONAL_VERSION_EXPIRED\":12001,\"LOCERR_PERSONAL_SECTION_ACCESS_DETECTED\":12002,\"LOCERR_PERSONAL_APP_DELETION_FAILED\":12003,\"LOCERR_USER_AUTHENTICATION_FAILURE\":12004,\"LOCERR_EXPORT_OUT_OF_MEMORY\":13000,\"LOCERR_EXPORT_NO_DATA\":13001,\"LOCERR_SYNC_INVALID_OFFSET\":14000,\"LOCERR_SEARCH_TIMEOUT\":15000,\"LOCERR_DIRECT_DISCOVERY_LINKED_EXPRESSION_FAIL\":16000,\"LOCERR_DIRECT_DISCOVERY_ROWCOUNT_OVERFLOW\":16001,\"LOCERR_DIRECT_DISCOVERY_EMPTY_RESULT\":16002,\"LOCERR_DIRECT_DISCOVERY_DB_CONNECTION_FAILED\":16003,\"LOCERR_DIRECT_DISCOVERY_MEASURE_NOT_ALLOWED\":16004,\"LOCERR_DIRECT_DISCOVERY_DETAIL_NOT_ALLOWED\":16005,\"LOCERR_DIRECT_DISCOVERY_NOT_SYNTH_CIRCULAR_ALLOWED\":16006,\"LOCERR_DIRECT_DISCOVERY_ONLY_ONE_DD_TABLE_ALLOWED\":16007,\"LOCERR_DIRECT_DISCOVERY_DB_AUTHORIZATION_FAILED\":16008,\"LOCERR_SMART_LOAD_TABLE_NOT_FOUND\":17000,\"LOCERR_SMART_LOAD_TABLE_DUPLICATED\":17001,\"LOCERR_VARIABLE_NO_NAME\":18000,\"LOCERR_VARIABLE_DUPLICATE_NAME\":18001,\"LOCERR_VARIABLE_INCONSISTENCY\":18002,\"LOCERR_MEDIA_LIBRARY_LIST_FAILED\":19000,\"LOCERR_MEDIA_LIBRARY_CONTENT_FAILED\":19001,\"LOCERR_MEDIA_BUNDLING_FAILED\":19002,\"LOCERR_MEDIA_UNBUNDLING_FAILED\":19003,\"LOCERR_MEDIA_LIBRARY_NOT_FOUND\":19004,\"LOCERR_FEATURE_DISABLED\":20000,\"LOCERR_JSON_RPC_INVALID_REQUEST\":-32600,\"LOCERR_JSON_RPC_METHOD_NOT_FOUND\":-32601,\"LOCERR_JSON_RPC_INVALID_PARAMETERS\":-32602,\"LOCERR_JSON_RPC_INTERNAL_ERROR\":-32603,\"LOCERR_JSON_RPC_PARSE_ERROR\":-32700,\"LOCERR_MQ_SOCKET_CONNECT_FAILURE\":33000,\"LOCERR_MQ_SOCKET_OPEN_FAILURE\":33001,\"LOCERR_MQ_PROTOCOL_NO_RESPONE\":33002,\"LOCERR_MQ_PROTOCOL_LIBRARY_EXCEPTION\":33003,\"LOCERR_MQ_PROTOCOL_CONNECTION_CLOSED\":33004,\"LOCERR_MQ_PROTOCOL_CHANNEL_CLOSED\":33005,\"LOCERR_MQ_PROTOCOL_UNKNOWN_ERROR\":33006,\"LOCERR_MQ_PROTOCOL_INVALID_STATUS\":33007,\"LOCERR_EXTENGINE_GRPC_STATUS_OK\":22000,\"LOCERR_EXTENGINE_GRPC_STATUS_CANCELLED\":22001,\"LOCERR_EXTENGINE_GRPC_STATUS_UNKNOWN\":22002,\"LOCERR_EXTENGINE_GRPC_STATUS_INVALID_ARGUMENT\":22003,\"LOCERR_EXTENGINE_GRPC_STATUS_DEADLINE_EXCEEDED\":22004,\"LOCERR_EXTENGINE_GRPC_STATUS_NOT_FOUND\":22005,\"LOCERR_EXTENGINE_GRPC_STATUS_ALREADY_EXISTS\":22006,\"LOCERR_EXTENGINE_GRPC_STATUS_PERMISSION_DENIED\":22007,\"LOCERR_EXTENGINE_GRPC_STATUS_RESOURCE_EXHAUSTED\":22008,\"LOCERR_EXTENGINE_GRPC_STATUS_FAILED_PRECONDITION\":22009,\"LOCERR_EXTENGINE_GRPC_STATUS_ABORTED\":22010,\"LOCERR_EXTENGINE_GRPC_STATUS_OUT_OF_RANGE\":22011,\"LOCERR_EXTENGINE_GRPC_STATUS_UNIMPLEMENTED\":22012,\"LOCERR_EXTENGINE_GRPC_STATUS_INTERNAL\":22013,\"LOCERR_EXTENGINE_GRPC_STATUS_UNAVAILABLE\":22014,\"LOCERR_EXTENGINE_GRPC_STATUS_DATA_LOSS\":22015,\"LOCERR_EXTENGINE_GRPC_STATUS_UNAUTHENTICATED\":22016,\"LOCERR_LXW_INVALID_OBJ\":23001,\"LOCERR_LXW_INVALID_FILE\":23002,\"LOCERR_LXW_INVALID_SHEET\":23003,\"LOCERR_LXW_INVALID_EXPORT_RANGE\":23004,\"LOCERR_LXW_ERROR\":23005,\"LOCERR_LXW_ERROR_MEMORY_MALLOC_FAILED\":23006,\"LOCERR_LXW_ERROR_CREATING_XLSX_FILE\":23007,\"LOCERR_LXW_ERROR_CREATING_TMPFILE\":23008,\"LOCERR_LXW_ERROR_ZIP_FILE_OPERATION\":23009,\"LOCERR_LXW_ERROR_ZIP_FILE_ADD\":23010,\"LOCERR_LXW_ERROR_ZIP_CLOSE\":23011,\"LOCERR_LXW_ERROR_NULL_PARAMETER_IGNORED\":23012,\"LOCERR_LXW_ERROR_MAX_STRING_LENGTH_EXCEEDED\":23013,\"LOCERR_LXW_ERROR_255_STRING_LENGTH_EXCEEDED\":23014,\"LOCERR_LXW_ERROR_SHARED_STRING_INDEX_NOT_FOUND\":23015,\"LOCERR_LXW_ERROR_WORKSHEET_INDEX_OUT_OF_RANGE\":23016,\"LOCERR_LXW_ERROR_WORKSHEET_MAX_NUMBER_URLS_EXCEEDED\":23017,\"LOCERR_CURL_UNSUPPORTED_PROTOCOL\":30000,\"LOCERR_CURL_COULDNT_RESOLVE_PROXY\":30001,\"LOCERR_CURL_COULDNT_CONNECT\":30002,\"LOCERR_CURL_REMOTE_ACCESS_DENIED\":30003,\"LOCERR_CURL_FTP_ACCEPT_FAILED\":30004,\"LOCERR_CURL_FTP_ACCEPT_TIMEOUT\":30005,\"LOCERR_CURL_FTP_CANT_GET_HOST\":30006,\"LOCERR_CURL_PARTIAL_FILE\":30007,\"LOCERR_CURL_QUOTE_ERROR\":30008,\"LOCERR_CURL_WRITE_ERROR\":30009,\"LOCERR_CURL_UPLOAD_FAILED\":30010,\"LOCERR_CURL_OUT_OF_MEMORY\":30011,\"LOCERR_CURL_OPERATION_TIMEDOUT\":30012,\"LOCERR_CURL_FTP_COULDNT_USE_REST\":30013,\"LOCERR_CURL_HTTP_POST_ERROR\":30014,\"LOCERR_CURL_SSL_CONNECT_ERROR\":30015,\"LOCERR_CURL_FILE_COULDNT_READ_FILE\":30016,\"LOCERR_CURL_LDAP_CANNOT_BIND\":30017,\"LOCERR_CURL_LDAP_SEARCH_FAILED\":30018,\"LOCERR_CURL_TOO_MANY_REDIRECTS\":30019,\"LOCERR_CURL_PEER_FAILED_VERIFICATION\":30020,\"LOCERR_CURL_GOT_NOTHING\":30021,\"LOCERR_CURL_SSL_ENGINE_NOTFOUND\":30022,\"LOCERR_CURL_SSL_ENGINE_SETFAILED\":30023,\"LOCERR_CURL_SSL_CERTPROBLEM\":30024,\"LOCERR_CURL_SSL_CIPHER\":30025,\"LOCERR_CURL_SSL_CACERT\":30026,\"LOCERR_CURL_BAD_CONTENT_ENCODING\":30027,\"LOCERR_CURL_LDAP_INVALID_URL\":30028,\"LOCERR_CURL_USE_SSL_FAILED\":30029,\"LOCERR_CURL_SSL_ENGINE_INITFAILED\":30030,\"LOCERR_CURL_LOGIN_DENIED\":30031,\"LOCERR_CURL_TFTP_NOTFOUND\":30032,\"LOCERR_CURL_TFTP_ILLEGAL\":30033,\"LOCERR_CURL_SSH\":30034},\"LocalizedWarningCode\":{\"LOCWARN_PERSONAL_RELOAD_REQUIRED\":0,\"LOCWARN_PERSONAL_VERSION_EXPIRES_SOON\":1,\"LOCWARN_EXPORT_DATA_TRUNCATED\":1000,\"LOCWARN_COULD_NOT_OPEN_ALL_OBJECTS\":2000},\"GrpType\":{\"GRP_NX_NONE\":0,\"GRP_NX_HIEARCHY\":1,\"GRP_NX_COLLECTION\":2},\"ExportFileType\":{\"EXPORT_CSV_C\":0,\"EXPORT_CSV_T\":1,\"EXPORT_OOXML\":2},\"ExportState\":{\"EXPORT_POSSIBLE\":0,\"EXPORT_ALL\":1},\"DimCellType\":{\"NX_DIM_CELL_VALUE\":0,\"NX_DIM_CELL_EMPTY\":1,\"NX_DIM_CELL_NORMAL\":2,\"NX_DIM_CELL_TOTAL\":3,\"NX_DIM_CELL_OTHER\":4,\"NX_DIM_CELL_AGGR\":5,\"NX_DIM_CELL_PSEUDO\":6,\"NX_DIM_CELL_ROOT\":7,\"NX_DIM_CELL_NULL\":8,\"NX_DIM_CELL_GENERATED\":9},\"StackElemType\":{\"NX_STACK_CELL_NORMAL\":0,\"NX_STACK_CELL_TOTAL\":1,\"NX_STACK_CELL_OTHER\":2,\"NX_STACK_CELL_SUM\":3,\"NX_STACK_CELL_VALUE\":4,\"NX_STACK_CELL_PSEUDO\":5},\"SortIndicatorType\":{\"NX_SORT_INDICATE_NONE\":0,\"NX_SORT_INDICATE_ASC\":1,\"NX_SORT_INDICATE_DESC\":2},\"DimensionType\":{\"NX_DIMENSION_TYPE_DISCRETE\":0,\"NX_DIMENSION_TYPE_NUMERIC\":1,\"NX_DIMENSION_TYPE_TIME\":2},\"FieldSelectionMode\":{\"SELECTION_MODE_NORMAL\":0,\"SELECTION_MODE_AND\":1,\"SELECTION_MODE_NOT\":2},\"FrequencyMode\":{\"NX_FREQUENCY_NONE\":0,\"NX_FREQUENCY_VALUE\":1,\"NX_FREQUENCY_PERCENT\":2,\"NX_FREQUENCY_RELATIVE\":3},\"DataReductionMode\":{\"DATA_REDUCTION_NONE\":0,\"DATA_REDUCTION_ONEDIM\":1,\"DATA_REDUCTION_SCATTERED\":2,\"DATA_REDUCTION_CLUSTERED\":3,\"DATA_REDUCTION_STACKED\":4},\"HypercubeMode\":{\"DATA_MODE_STRAIGHT\":0,\"DATA_MODE_PIVOT\":1,\"DATA_MODE_PIVOT_STACK\":2,\"DATA_MODE_TREE\":3},\"PatchOperationType\":{\"Add\":0,\"Remove\":1,\"Replace\":2},\"SelectionCellType\":{\"NX_CELL_DATA\":0,\"NX_CELL_TOP\":1,\"NX_CELL_LEFT\":2},\"MatchingFieldMode\":{\"MATCHINGFIELDMODE_MATCH_ALL\":0,\"MATCHINGFIELDMODE_MATCH_ONE\":1},\"SessionState\":{\"SESSION_CREATED\":0,\"SESSION_ATTACHED\":1,\"SESSION_ERROR_NO_LICENSE\":2,\"SESSION_ERROR_LICENSE_RENEW\":3},\"ReloadState\":{\"RELOAD_PAUSED\":0,\"RELOAD_STARTED\":1,\"RELOAD_ABORTED\":2},\"QrsChangeType\":{\"QRS_CHANGE_UNDEFINED\":0,\"QRS_CHANGE_ADD\":1,\"QRS_CHANGE_UPDATE\":2,\"QRS_CHANGE_DELETE\":3},\"ExtEngineDataType\":{\"NX_EXT_DATATYPE_STRING\":0,\"NX_EXT_DATATYPE_DOUBLE\":1,\"NX_EXT_DATATYPE_BOTH\":2},\"ExtEngineFunctionType\":{\"NX_EXT_FUNCTIONTYPE_SCALAR\":0,\"NX_EXT_FUNCTIONTYPE_AGGR\":1,\"NX_EXT_FUNCTIONTYPE_TENSOR\":2},\"ExtEngineMsgType\":{\"NX_EXT_MSGTYPE_FUNCTION_CALL\":1,\"NX_EXT_MSGTYPE_SCRIPT_CALL\":2,\"NX_EXT_MSGTYPE_RETURN_VALUE\":3,\"NX_EXT_MSGTYPE_RETURN_MULTIPLE\":4,\"NX_EXT_MSGTYPE_RETURN_ERROR\":5}},\"version\":\"12.170.2\"}"); /***/ }), /* 92 */ /***/ (function(module, exports, __webpack_require__) { /** * enigma.js v2.6.3 * Copyright (c) 2019 QlikTech International AB * This library is licensed under MIT - See the LICENSE file for full details */ (function (global, factory) { true ? module.exports = factory() : undefined; }(this, (function () { 'use strict'; function createCommonjsModule(fn, module) { return module = { exports: {} }, fn(module, module.exports), module.exports; } // Copyright Joyent, Inc. and other Node contributors. // If obj.hasOwnProperty has been overridden, then calling // obj.hasOwnProperty(prop) will break. // See: https://github.com/joyent/node/issues/1707 function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } var decode = function(qs, sep, eq, options) { sep = sep || '&'; eq = eq || '='; var obj = {}; if (typeof qs !== 'string' || qs.length === 0) { return obj; } var regexp = /\+/g; qs = qs.split(sep); var maxKeys = 1000; if (options && typeof options.maxKeys === 'number') { maxKeys = options.maxKeys; } var len = qs.length; // maxKeys <= 0 means that we should not limit keys count if (maxKeys > 0 && len > maxKeys) { len = maxKeys; } for (var i = 0; i < len; ++i) { var x = qs[i].replace(regexp, '%20'), idx = x.indexOf(eq), kstr, vstr, k, v; if (idx >= 0) { kstr = x.substr(0, idx); vstr = x.substr(idx + 1); } else { kstr = x; vstr = ''; } k = decodeURIComponent(kstr); v = decodeURIComponent(vstr); if (!hasOwnProperty(obj, k)) { obj[k] = v; } else if (Array.isArray(obj[k])) { obj[k].push(v); } else { obj[k] = [obj[k], v]; } } return obj; }; // Copyright Joyent, Inc. and other Node contributors. var stringifyPrimitive = function(v) { switch (typeof v) { case 'string': return v; case 'boolean': return v ? 'true' : 'false'; case 'number': return isFinite(v) ? v : ''; default: return ''; } }; var encode = function(obj, sep, eq, name) { sep = sep || '&'; eq = eq || '='; if (obj === null) { obj = undefined; } if (typeof obj === 'object') { return Object.keys(obj).map(function(k) { var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; if (Array.isArray(obj[k])) { return obj[k].map(function(v) { return ks + encodeURIComponent(stringifyPrimitive(v)); }).join(sep); } else { return ks + encodeURIComponent(stringifyPrimitive(obj[k])); } }).join(sep); } if (!name) return ''; return encodeURIComponent(stringifyPrimitive(name)) + eq + encodeURIComponent(stringifyPrimitive(obj)); }; var querystring = createCommonjsModule(function (module, exports) { exports.decode = exports.parse = decode; exports.encode = exports.stringify = encode; }); var querystring_1 = querystring.decode; var querystring_2 = querystring.parse; var querystring_3 = querystring.encode; var querystring_4 = querystring.stringify; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } /** * The Qlik Sense configuration object. * @typedef {Object} SenseConfiguration * @property {String} [appId] The app id. If omitted, only the global object is returned. * Otherwise both global and app object are returned. * @property {Boolean} [noData=false] Whether to open the app without data. * @property {Boolean} [secure=true] Set to false if an unsecure WebSocket should be used. * @property {String} [host] Host address. * @property {Number} [port] Port to connect to. * @property {String} [prefix="/"] The absolute base path to use when connecting. * Used for proxy prefixes. * @property {String} [subpath=""] The subpath. * @property {String} [route=""] Used to instruct Proxy to route to the correct receiver. * @property {String} [identity=""] Identity to use. * @property {Object} [urlParams={}] Used to add parameters to the WebSocket URL. * @property {Number} [ttl] A value in seconds that QIX Engine should keep the session * alive after socket disconnect (only works if QIX Engine supports it). */ function replaceLeadingAndTrailingSlashes(str) { return str.replace(/(^[/]+)|([/]+$)/g, ''); } var SenseUtilities = /*#__PURE__*/ function () { function SenseUtilities() { _classCallCheck(this, SenseUtilities); } _createClass(SenseUtilities, null, [{ key: "configureDefaults", /** * Ensures that the configuration has defaults set. * * @private * @param {SenseConfiguration} senseConfig The configuration to ensure defaults on. */ value: function configureDefaults(senseConfig) { if (!senseConfig.host) { senseConfig.host = 'localhost'; } if (typeof senseConfig.secure === 'undefined') { senseConfig.secure = true; } if (!senseConfig.appId && !senseConfig.route) { senseConfig.route = 'app/engineData'; } if (typeof senseConfig.noData === 'undefined') { senseConfig.noData = false; } } /** * Function used to build an URL. * @param {SenseConfiguration} urlConfig - The URL configuration object. * @returns {String} Returns the websocket URL. */ }, { key: "buildUrl", value: function buildUrl(urlConfig) { SenseUtilities.configureDefaults(urlConfig); var secure = urlConfig.secure, host = urlConfig.host, port = urlConfig.port, prefix = urlConfig.prefix, subpath = urlConfig.subpath, route = urlConfig.route, identity = urlConfig.identity, urlParams = urlConfig.urlParams, ttl = urlConfig.ttl, appId = urlConfig.appId; var url = ''; url += "".concat(secure ? 'wss' : 'ws', "://"); url += host || 'localhost'; if (port) { url += ":".concat(port); } if (prefix) { url += "/".concat(replaceLeadingAndTrailingSlashes(prefix)); } if (subpath) { url += "/".concat(replaceLeadingAndTrailingSlashes(subpath)); } if (route) { url += "/".concat(replaceLeadingAndTrailingSlashes(route)); } else if (appId) { url += "/app/".concat(encodeURIComponent(appId)); } if (identity) { url += "/identity/".concat(encodeURIComponent(identity)); } if (ttl) { url += "/ttl/".concat(ttl); } if (urlParams) { url += "?".concat(querystring.stringify(urlParams)); } return url; } }]); return SenseUtilities; }(); return SenseUtilities; }))); //# sourceMappingURL=sense-utilities.js.map /***/ }), /* 93 */ /***/ (function(module, exports) { function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } module.exports = _arrayWithHoles; /***/ }), /* 94 */ /***/ (function(module, exports) { function _iterableToArrayLimit(arr, i) { if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === "[object Arguments]")) { return; } var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } module.exports = _iterableToArrayLimit; /***/ }), /* 95 */ /***/ (function(module, exports) { function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } module.exports = _nonIterableRest; /***/ }), /* 96 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var keysShim; if (!Object.keys) { // modified from https://github.com/es-shims/es5-shim var has = Object.prototype.hasOwnProperty; var toStr = Object.prototype.toString; var isArgs = __webpack_require__(54); // eslint-disable-line global-require var isEnumerable = Object.prototype.propertyIsEnumerable; var hasDontEnumBug = !isEnumerable.call({ toString: null }, 'toString'); var hasProtoEnumBug = isEnumerable.call(function () {}, 'prototype'); var dontEnums = [ 'toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor' ]; var equalsConstructorPrototype = function (o) { var ctor = o.constructor; return ctor && ctor.prototype === o; }; var excludedKeys = { $applicationCache: true, $console: true, $external: true, $frame: true, $frameElement: true, $frames: true, $innerHeight: true, $innerWidth: true, $onmozfullscreenchange: true, $onmozfullscreenerror: true, $outerHeight: true, $outerWidth: true, $pageXOffset: true, $pageYOffset: true, $parent: true, $scrollLeft: true, $scrollTop: true, $scrollX: true, $scrollY: true, $self: true, $webkitIndexedDB: true, $webkitStorageInfo: true, $window: true }; var hasAutomationEqualityBug = (function () { /* global window */ if (typeof window === 'undefined') { return false; } for (var k in window) { try { if (!excludedKeys['$' + k] && has.call(window, k) && window[k] !== null && typeof window[k] === 'object') { try { equalsConstructorPrototype(window[k]); } catch (e) { return true; } } } catch (e) { return true; } } return false; }()); var equalsConstructorPrototypeIfNotBuggy = function (o) { /* global window */ if (typeof window === 'undefined' || !hasAutomationEqualityBug) { return equalsConstructorPrototype(o); } try { return equalsConstructorPrototype(o); } catch (e) { return false; } }; keysShim = function keys(object) { var isObject = object !== null && typeof object === 'object'; var isFunction = toStr.call(object) === '[object Function]'; var isArguments = isArgs(object); var isString = isObject && toStr.call(object) === '[object String]'; var theKeys = []; if (!isObject && !isFunction && !isArguments) { throw new TypeError('Object.keys called on a non-object'); } var skipProto = hasProtoEnumBug && isFunction; if (isString && object.length > 0 && !has.call(object, 0)) { for (var i = 0; i < object.length; ++i) { theKeys.push(String(i)); } } if (isArguments && object.length > 0) { for (var j = 0; j < object.length; ++j) { theKeys.push(String(j)); } } else { for (var name in object) { if (!(skipProto && name === 'prototype') && has.call(object, name)) { theKeys.push(String(name)); } } } if (hasDontEnumBug) { var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object); for (var k = 0; k < dontEnums.length; ++k) { if (!(skipConstructor && dontEnums[k] === 'constructor') && has.call(object, dontEnums[k])) { theKeys.push(dontEnums[k]); } } } return theKeys; }; } module.exports = keysShim; /***/ }), /* 97 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // http://www.ecma-international.org/ecma-262/6.0/#sec-object.is var numberIsNaN = function (value) { return value !== value; }; module.exports = function is(a, b) { if (a === 0 && b === 0) { return 1 / a === 1 / b; } if (a === b) { return true; } if (numberIsNaN(a) && numberIsNaN(b)) { return true; } return false; }; /***/ }), /* 98 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var has = __webpack_require__(99); var regexExec = RegExp.prototype.exec; var gOPD = Object.getOwnPropertyDescriptor; var tryRegexExecCall = function tryRegexExec(value) { try { var lastIndex = value.lastIndex; value.lastIndex = 0; // eslint-disable-line no-param-reassign regexExec.call(value); return true; } catch (e) { return false; } finally { value.lastIndex = lastIndex; // eslint-disable-line no-param-reassign } }; var toStr = Object.prototype.toString; var regexClass = '[object RegExp]'; var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; module.exports = function isRegex(value) { if (!value || typeof value !== 'object') { return false; } if (!hasToStringTag) { return toStr.call(value) === regexClass; } var descriptor = gOPD(value, 'lastIndex'); var hasLastIndexDataProperty = descriptor && has(descriptor, 'value'); if (!hasLastIndexDataProperty) { return false; } return tryRegexExecCall(value); }; /***/ }), /* 99 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var bind = __webpack_require__(40); module.exports = bind.call(Function.call, Object.prototype.hasOwnProperty); /***/ }), /* 100 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* eslint no-invalid-this: 1 */ var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; var slice = Array.prototype.slice; var toStr = Object.prototype.toString; var funcType = '[object Function]'; module.exports = function bind(that) { var target = this; if (typeof target !== 'function' || toStr.call(target) !== funcType) { throw new TypeError(ERROR_MESSAGE + target); } var args = slice.call(arguments, 1); var bound; var binder = function () { if (this instanceof bound) { var result = target.apply( this, args.concat(slice.call(arguments)) ); if (Object(result) === result) { return result; } return this; } else { return target.apply( that, args.concat(slice.call(arguments)) ); } }; var boundLength = Math.max(0, target.length - args.length); var boundArgs = []; for (var i = 0; i < boundLength; i++) { boundArgs.push('$' + i); } bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder); if (target.prototype) { var Empty = function Empty() {}; Empty.prototype = target.prototype; bound.prototype = new Empty(); Empty.prototype = null; } return bound; }; /***/ }), /* 101 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var define = __webpack_require__(41); var callBind = __webpack_require__(56); var implementation = __webpack_require__(58); var getPolyfill = __webpack_require__(59); var shim = __webpack_require__(102); var flagsBound = callBind(implementation); define(flagsBound, { getPolyfill: getPolyfill, implementation: implementation, shim: shim }); module.exports = flagsBound; /***/ }), /* 102 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var supportsDescriptors = __webpack_require__(41).supportsDescriptors; var getPolyfill = __webpack_require__(59); var gOPD = Object.getOwnPropertyDescriptor; var defineProperty = Object.defineProperty; var TypeErr = TypeError; var getProto = Object.getPrototypeOf; var regex = /a/; module.exports = function shimFlags() { if (!supportsDescriptors || !getProto) { throw new TypeErr('RegExp.prototype.flags requires a true ES5 environment that supports property descriptors'); } var polyfill = getPolyfill(); var proto = getProto(regex); var descriptor = gOPD(proto, 'flags'); if (!descriptor || descriptor.get !== polyfill) { defineProperty(proto, 'flags', { configurable: true, enumerable: false, get: polyfill }); } return polyfill; }; /***/ }), /* 103 */ /***/ (function(module, exports) { var toString = {}.toString; module.exports = Array.isArray || function (arr) { return toString.call(arr) == '[object Array]'; }; /***/ }), /* 104 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var getDay = Date.prototype.getDay; var tryDateObject = function tryDateGetDayCall(value) { try { getDay.call(value); return true; } catch (e) { return false; } }; var toStr = Object.prototype.toString; var dateClass = '[object Date]'; var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; module.exports = function isDateObject(value) { if (typeof value !== 'object' || value === null) { return false; } return hasToStringTag ? tryDateObject(value) : toStr.call(value) === dateClass; }; /***/ }), /* 105 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var isString = __webpack_require__(60); var isNumber = __webpack_require__(106); var isBoolean = __webpack_require__(107); var isSymbol = __webpack_require__(108); var isBigInt = __webpack_require__(109); // eslint-disable-next-line consistent-return module.exports = function whichBoxedPrimitive(value) { // eslint-disable-next-line eqeqeq if (value == null || (typeof value !== 'object' && typeof value !== 'function')) { return null; } if (isString(value)) { return 'String'; } if (isNumber(value)) { return 'Number'; } if (isBoolean(value)) { return 'Boolean'; } if (isSymbol(value)) { return 'Symbol'; } if (isBigInt(value)) { return 'BigInt'; } }; /***/ }), /* 106 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var numToStr = Number.prototype.toString; var tryNumberObject = function tryNumberObject(value) { try { numToStr.call(value); return true; } catch (e) { return false; } }; var toStr = Object.prototype.toString; var numClass = '[object Number]'; var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; module.exports = function isNumberObject(value) { if (typeof value === 'number') { return true; } if (typeof value !== 'object') { return false; } return hasToStringTag ? tryNumberObject(value) : toStr.call(value) === numClass; }; /***/ }), /* 107 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var boolToStr = Boolean.prototype.toString; var tryBooleanObject = function booleanBrandCheck(value) { try { boolToStr.call(value); return true; } catch (e) { return false; } }; var toStr = Object.prototype.toString; var boolClass = '[object Boolean]'; var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; module.exports = function isBoolean(value) { if (typeof value === 'boolean') { return true; } if (value === null || typeof value !== 'object') { return false; } return hasToStringTag && Symbol.toStringTag in value ? tryBooleanObject(value) : toStr.call(value) === boolClass; }; /***/ }), /* 108 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var toStr = Object.prototype.toString; var hasSymbols = __webpack_require__(42)(); if (hasSymbols) { var symToStr = Symbol.prototype.toString; var symStringRegex = /^Symbol\(.*\)$/; var isSymbolObject = function isRealSymbolObject(value) { if (typeof value.valueOf() !== 'symbol') { return false; } return symStringRegex.test(symToStr.call(value)); }; module.exports = function isSymbol(value) { if (typeof value === 'symbol') { return true; } if (toStr.call(value) !== '[object Symbol]') { return false; } try { return isSymbolObject(value); } catch (e) { return false; } }; } else { module.exports = function isSymbol(value) { // this environment does not support Symbols. return false && false; }; } /***/ }), /* 109 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; if (typeof BigInt === 'function') { var bigIntValueOf = BigInt.prototype.valueOf; var tryBigInt = function tryBigIntObject(value) { try { bigIntValueOf.call(value); return true; } catch (e) { } return false; }; module.exports = function isBigInt(value) { if ( value === null || typeof value === 'undefined' || typeof value === 'boolean' || typeof value === 'string' || typeof value === 'number' || typeof value === 'symbol' || typeof value === 'function' ) { return false; } if (typeof value === 'bigint') { // eslint-disable-line valid-typeof return true; } return tryBigInt(value); }; } else { module.exports = function isBigInt(value) { return false && false; }; } /***/ }), /* 110 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var isMap = __webpack_require__(61); var isSet = __webpack_require__(62); var isWeakMap = __webpack_require__(111); var isWeakSet = __webpack_require__(112); module.exports = function whichCollection(value) { if (value && typeof value === 'object') { if (isMap(value)) { return 'Map'; } if (isSet(value)) { return 'Set'; } if (isWeakMap(value)) { return 'WeakMap'; } if (isWeakSet(value)) { return 'WeakSet'; } } return false; }; /***/ }), /* 111 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var $WeakMap = typeof WeakMap === 'function' && WeakMap.prototype ? WeakMap : null; var $WeakSet = typeof WeakSet === 'function' && WeakSet.prototype ? WeakSet : null; var exported; if (!$WeakMap) { // eslint-disable-next-line no-unused-vars exported = function isWeakMap(x) { // `WeakMap` is not present in this environment. return false; }; } var $mapHas = $WeakMap ? $WeakMap.prototype.has : null; var $setHas = $WeakSet ? $WeakSet.prototype.has : null; if (!exported && !$mapHas) { // eslint-disable-next-line no-unused-vars exported = function isWeakMap(x) { // `WeakMap` does not have a `has` method return false; }; } module.exports = exported || function isWeakMap(x) { if (!x || typeof x !== 'object') { return false; } try { $mapHas.call(x, $mapHas); if ($setHas) { try { $setHas.call(x, $setHas); } catch (e) { return true; } } return x instanceof $WeakMap; // core-js workaround, pre-v3 } catch (e) {} return false; }; /***/ }), /* 112 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var $WeakMap = typeof WeakMap === 'function' && WeakMap.prototype ? WeakMap : null; var $WeakSet = typeof WeakSet === 'function' && WeakSet.prototype ? WeakSet : null; var exported; if (!$WeakMap) { // eslint-disable-next-line no-unused-vars exported = function isWeakSet(x) { // `WeakSet` is not present in this environment. return false; }; } var $mapHas = $WeakMap ? $WeakMap.prototype.has : null; var $setHas = $WeakSet ? $WeakSet.prototype.has : null; if (!exported && !$setHas) { // eslint-disable-next-line no-unused-vars module.exports = function isWeakSet(x) { // `WeakSet` does not have a `has` method return false; }; } module.exports = exported || function isWeakSet(x) { if (!x || typeof x !== 'object') { return false; } try { $setHas.call(x, $setHas); if ($mapHas) { try { $mapHas.call(x, $mapHas); } catch (e) { return true; } } return x instanceof $WeakSet; // core-js workaround, pre-v3 } catch (e) {} return false; }; /***/ }), /* 113 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* WEBPACK VAR INJECTION */(function(process) { /* eslint global-require: 0 */ // the code is structured this way so that bundlers can // alias out `has-symbols` to `() => true` or `() => false` if your target // environments' Symbol capabilities are known, and then use // dead code elimination on the rest of this module. // // Similarly, `isarray` can be aliased to `Array.isArray` if // available in all target environments. var isArguments = __webpack_require__(55); if (__webpack_require__(42)() || __webpack_require__(57)()) { var $iterator = Symbol.iterator; // Symbol is available natively or shammed // natively: // - Chrome >= 38 // - Edge 12-14?, Edge >= 15 for sure // - FF >= 36 // - Safari >= 9 // - node >= 0.12 module.exports = function getIterator(iterable) { // alternatively, `iterable[$iterator]?.()` if (iterable != null && typeof iterable[$iterator] !== 'undefined') { return iterable[$iterator](); } if (isArguments(iterable)) { // arguments objects lack Symbol.iterator // - node 0.12 return Array.prototype[$iterator].call(iterable); } }; } else { // Symbol is not available, native or shammed var isArray = __webpack_require__(115); var isString = __webpack_require__(60); var GetIntrinsic = __webpack_require__(30); var $Map = GetIntrinsic('%Map%', true); var $Set = GetIntrinsic('%Set%', true); var callBound = __webpack_require__(43); var $arrayPush = callBound('Array.prototype.push'); var $charCodeAt = callBound('String.prototype.charCodeAt'); var $stringSlice = callBound('String.prototype.slice'); var advanceStringIndex = function advanceStringIndex(S, index) { var length = S.length; if ((index + 1) >= length) { return index + 1; } var first = $charCodeAt(S, index); if (first < 0xD800 || first > 0xDBFF) { return index + 1; } var second = $charCodeAt(S, index + 1); if (second < 0xDC00 || second > 0xDFFF) { return index + 1; } return index + 2; }; var getArrayIterator = function getArrayIterator(arraylike) { var i = 0; return { next: function next() { var done = i >= arraylike.length; var value; if (!done) { value = arraylike[i]; i += 1; } return { done: done, value: value }; } }; }; var getNonCollectionIterator = function getNonCollectionIterator(iterable) { if (isArray(iterable) || isArguments(iterable)) { return getArrayIterator(iterable); } if (isString(iterable)) { var i = 0; return { next: function next() { var nextIndex = advanceStringIndex(iterable, i); var value = $stringSlice(iterable, i, nextIndex); i = nextIndex; return { done: nextIndex > iterable.length, value: value }; } }; } }; if (!$Map && !$Set) { // the only language iterables are Array, String, arguments // - Safari <= 6.0 // - Chrome < 38 // - node < 0.12 // - FF < 13 // - IE < 11 // - Edge < 11 module.exports = getNonCollectionIterator; } else { // either Map or Set are available, but Symbol is not // - es6-shim on an ES5 browser // - Safari 6.2 (maybe 6.1?) // - FF v[13, 36) // - IE 11 // - Edge 11 // - Safari v[6, 9) var isMap = __webpack_require__(61); var isSet = __webpack_require__(62); // Firefox >= 27, IE 11, Safari 6.2 - 9, Edge 11, es6-shim in older envs, all have forEach var $mapForEach = callBound('Map.prototype.forEach', true); var $setForEach = callBound('Set.prototype.forEach', true); if (typeof process === 'undefined' || !process.versions || !process.versions.node) { // "if is not node" // Firefox 17 - 26 has `.iterator()`, whose iterator `.next()` either // returns a value, or throws a StopIteration object. These browsers // do not have any other mechanism for iteration. var $mapIterator = callBound('Map.prototype.iterator', true); var $setIterator = callBound('Set.prototype.iterator', true); var getStopIterationIterator = function (iterator) { var done = false; return { next: function next() { try { return { done: done, value: done ? undefined : iterator.next() }; } catch (e) { done = true; return { done: true, value: undefined }; } } }; }; } // Firefox 27-35, and some older es6-shim versions, use a string "@@iterator" property // this returns a proper iterator object, so we should use it instead of forEach. // newer es6-shim versions use a string "_es6-shim iterator_" property. var $mapAtAtIterator = callBound('Map.prototype.@@iterator', true) || callBound('Map.prototype._es6-shim iterator_', true); var $setAtAtIterator = callBound('Set.prototype.@@iterator', true) || callBound('Set.prototype._es6-shim iterator_', true); var getCollectionIterator = function getCollectionIterator(iterable) { if (isMap(iterable)) { if ($mapIterator) { return getStopIterationIterator($mapIterator(iterable)); } if ($mapAtAtIterator) { return $mapAtAtIterator(iterable); } if ($mapForEach) { var entries = []; $mapForEach(iterable, function (v, k) { $arrayPush(entries, [k, v]); }); return getArrayIterator(entries); } } if (isSet(iterable)) { if ($setIterator) { return getStopIterationIterator($setIterator(iterable)); } if ($setAtAtIterator) { return $setAtAtIterator(iterable); } if ($setForEach) { var values = []; $setForEach(iterable, function (v) { $arrayPush(values, v); }); return getArrayIterator(values); } } }; module.exports = function getIterator(iterable) { return getCollectionIterator(iterable) || getNonCollectionIterator(iterable); }; } } /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(114))) /***/ }), /* 114 */ /***/ (function(module, exports) { // shim for using process in browser var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it // don't break things. But we need to wrap it in a try catch in case it is // wrapped in strict mode code which doesn't define any globals. It's inside a // function because try/catches deoptimize in certain engines. var cachedSetTimeout; var cachedClearTimeout; function defaultSetTimout() { throw new Error('setTimeout has not been defined'); } function defaultClearTimeout () { throw new Error('clearTimeout has not been defined'); } (function () { try { if (typeof setTimeout === 'function') { cachedSetTimeout = setTimeout; } else { cachedSetTimeout = defaultSetTimout; } } catch (e) { cachedSetTimeout = defaultSetTimout; } try { if (typeof clearTimeout === 'function') { cachedClearTimeout = clearTimeout; } else { cachedClearTimeout = defaultClearTimeout; } } catch (e) { cachedClearTimeout = defaultClearTimeout; } } ()) function runTimeout(fun) { if (cachedSetTimeout === setTimeout) { //normal enviroments in sane situations return setTimeout(fun, 0); } // if setTimeout wasn't available but was latter defined if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { cachedSetTimeout = setTimeout; return setTimeout(fun, 0); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedSetTimeout(fun, 0); } catch(e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedSetTimeout.call(null, fun, 0); } catch(e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error return cachedSetTimeout.call(this, fun, 0); } } } function runClearTimeout(marker) { if (cachedClearTimeout === clearTimeout) { //normal enviroments in sane situations return clearTimeout(marker); } // if clearTimeout wasn't available but was latter defined if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { cachedClearTimeout = clearTimeout; return clearTimeout(marker); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedClearTimeout(marker); } catch (e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedClearTimeout.call(null, marker); } catch (e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. // Some versions of I.E. have different rules for clearTimeout vs setTimeout return cachedClearTimeout.call(this, marker); } } } var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = runTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; runClearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { runTimeout(drainQueue); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.prependListener = noop; process.prependOnceListener = noop; process.listeners = function (name) { return [] } process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; /***/ }), /* 115 */ /***/ (function(module, exports) { var toString = {}.toString; module.exports = Array.isArray || function (arr) { return toString.call(arr) == '[object Array]'; }; /***/ }), /* 116 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var GetIntrinsic = __webpack_require__(30); var callBound = __webpack_require__(43); var inspect = __webpack_require__(117); var $TypeError = GetIntrinsic('%TypeError%'); var $WeakMap = GetIntrinsic('%WeakMap%', true); var $Map = GetIntrinsic('%Map%', true); var $push = callBound('Array.prototype.push'); var $weakMapGet = callBound('WeakMap.prototype.get', true); var $weakMapSet = callBound('WeakMap.prototype.set', true); var $weakMapHas = callBound('WeakMap.prototype.has', true); var $mapGet = callBound('Map.prototype.get', true); var $mapSet = callBound('Map.prototype.set', true); var $mapHas = callBound('Map.prototype.has', true); var objectGet = function (objects, key) { // eslint-disable-line consistent-return for (var i = 0; i < objects.length; i += 1) { if (objects[i].key === key) { return objects[i].value; } } }; var objectSet = function (objects, key, value) { for (var i = 0; i < objects.length; i += 1) { if (objects[i].key === key) { objects[i].value = value; // eslint-disable-line no-param-reassign return; } } $push(objects, { key: key, value: value }); }; var objectHas = function (objects, key) { for (var i = 0; i < objects.length; i += 1) { if (objects[i].key === key) { return true; } } return false; }; module.exports = function getSideChannel() { var $wm; var $m; var $o; var channel = { assert: function (key) { if (!channel.has(key)) { throw new $TypeError('Side channel does not contain ' + inspect(key)); } }, get: function (key) { // eslint-disable-line consistent-return if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { if ($wm) { return $weakMapGet($wm, key); } } else if ($Map) { if ($m) { return $mapGet($m, key); } } else { if ($o) { // eslint-disable-line no-lonely-if return objectGet($o, key); } } }, has: function (key) { if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { if ($wm) { return $weakMapHas($wm, key); } } else if ($Map) { if ($m) { return $mapHas($m, key); } } else { if ($o) { // eslint-disable-line no-lonely-if return objectHas($o, key); } } return false; }, set: function (key, value) { if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { if (!$wm) { $wm = new $WeakMap(); } $weakMapSet($wm, key, value); } else if ($Map) { if (!$m) { $m = new $Map(); } $mapSet($m, key, value); } else { if (!$o) { $o = []; } objectSet($o, key, value); } } }; return channel; }; /***/ }), /* 117 */ /***/ (function(module, exports, __webpack_require__) { var hasMap = typeof Map === 'function' && Map.prototype; var mapSizeDescriptor = Object.getOwnPropertyDescriptor && hasMap ? Object.getOwnPropertyDescriptor(Map.prototype, 'size') : null; var mapSize = hasMap && mapSizeDescriptor && typeof mapSizeDescriptor.get === 'function' ? mapSizeDescriptor.get : null; var mapForEach = hasMap && Map.prototype.forEach; var hasSet = typeof Set === 'function' && Set.prototype; var setSizeDescriptor = Object.getOwnPropertyDescriptor && hasSet ? Object.getOwnPropertyDescriptor(Set.prototype, 'size') : null; var setSize = hasSet && setSizeDescriptor && typeof setSizeDescriptor.get === 'function' ? setSizeDescriptor.get : null; var setForEach = hasSet && Set.prototype.forEach; var hasWeakMap = typeof WeakMap === 'function' && WeakMap.prototype; var weakMapHas = hasWeakMap ? WeakMap.prototype.has : null; var hasWeakSet = typeof WeakSet === 'function' && WeakSet.prototype; var weakSetHas = hasWeakSet ? WeakSet.prototype.has : null; var booleanValueOf = Boolean.prototype.valueOf; var objectToString = Object.prototype.toString; var match = String.prototype.match; var bigIntValueOf = typeof BigInt === 'function' ? BigInt.prototype.valueOf : null; var inspectCustom = __webpack_require__(118).custom; var inspectSymbol = inspectCustom && isSymbol(inspectCustom) ? inspectCustom : null; module.exports = function inspect_(obj, options, depth, seen) { var opts = options || {}; if (has(opts, 'quoteStyle') && (opts.quoteStyle !== 'single' && opts.quoteStyle !== 'double')) { throw new TypeError('option "quoteStyle" must be "single" or "double"'); } if (typeof obj === 'undefined') { return 'undefined'; } if (obj === null) { return 'null'; } if (typeof obj === 'boolean') { return obj ? 'true' : 'false'; } if (typeof obj === 'string') { return inspectString(obj, opts); } if (typeof obj === 'number') { if (obj === 0) { return Infinity / obj > 0 ? '0' : '-0'; } return String(obj); } if (typeof obj === 'bigint') { // eslint-disable-line valid-typeof return String(obj) + 'n'; } var maxDepth = typeof opts.depth === 'undefined' ? 5 : opts.depth; if (typeof depth === 'undefined') { depth = 0; } if (depth >= maxDepth && maxDepth > 0 && typeof obj === 'object') { return '[Object]'; } if (typeof seen === 'undefined') { seen = []; } else if (indexOf(seen, obj) >= 0) { return '[Circular]'; } function inspect(value, from) { if (from) { seen = seen.slice(); seen.push(from); } return inspect_(value, opts, depth + 1, seen); } if (typeof obj === 'function') { var name = nameOf(obj); return '[Function' + (name ? ': ' + name : '') + ']'; } if (isSymbol(obj)) { var symString = Symbol.prototype.toString.call(obj); return typeof obj === 'object' ? markBoxed(symString) : symString; } if (isElement(obj)) { var s = '<' + String(obj.nodeName).toLowerCase(); var attrs = obj.attributes || []; for (var i = 0; i < attrs.length; i++) { s += ' ' + attrs[i].name + '=' + wrapQuotes(quote(attrs[i].value), 'double', opts); } s += '>'; if (obj.childNodes && obj.childNodes.length) { s += '...'; } s += ''; return s; } if (isArray(obj)) { if (obj.length === 0) { return '[]'; } return '[ ' + arrObjKeys(obj, inspect).join(', ') + ' ]'; } if (isError(obj)) { var parts = arrObjKeys(obj, inspect); if (parts.length === 0) { return '[' + String(obj) + ']'; } return '{ [' + String(obj) + '] ' + parts.join(', ') + ' }'; } if (typeof obj === 'object') { if (inspectSymbol && typeof obj[inspectSymbol] === 'function') { return obj[inspectSymbol](); } else if (typeof obj.inspect === 'function') { return obj.inspect(); } } if (isMap(obj)) { var mapParts = []; mapForEach.call(obj, function (value, key) { mapParts.push(inspect(key, obj) + ' => ' + inspect(value, obj)); }); return collectionOf('Map', mapSize.call(obj), mapParts); } if (isSet(obj)) { var setParts = []; setForEach.call(obj, function (value) { setParts.push(inspect(value, obj)); }); return collectionOf('Set', setSize.call(obj), setParts); } if (isWeakMap(obj)) { return weakCollectionOf('WeakMap'); } if (isWeakSet(obj)) { return weakCollectionOf('WeakSet'); } if (isNumber(obj)) { return markBoxed(inspect(Number(obj))); } if (isBigInt(obj)) { return markBoxed(inspect(bigIntValueOf.call(obj))); } if (isBoolean(obj)) { return markBoxed(booleanValueOf.call(obj)); } if (isString(obj)) { return markBoxed(inspect(String(obj))); } if (!isDate(obj) && !isRegExp(obj)) { var xs = arrObjKeys(obj, inspect); if (xs.length === 0) { return '{}'; } return '{ ' + xs.join(', ') + ' }'; } return String(obj); }; function wrapQuotes(s, defaultStyle, opts) { var quoteChar = (opts.quoteStyle || defaultStyle) === 'double' ? '"' : "'"; return quoteChar + s + quoteChar; } function quote(s) { return String(s).replace(/"/g, '"'); } function isArray(obj) { return toStr(obj) === '[object Array]'; } function isDate(obj) { return toStr(obj) === '[object Date]'; } function isRegExp(obj) { return toStr(obj) === '[object RegExp]'; } function isError(obj) { return toStr(obj) === '[object Error]'; } function isSymbol(obj) { return toStr(obj) === '[object Symbol]'; } function isString(obj) { return toStr(obj) === '[object String]'; } function isNumber(obj) { return toStr(obj) === '[object Number]'; } function isBigInt(obj) { return toStr(obj) === '[object BigInt]'; } function isBoolean(obj) { return toStr(obj) === '[object Boolean]'; } var hasOwn = Object.prototype.hasOwnProperty || function (key) { return key in this; }; function has(obj, key) { return hasOwn.call(obj, key); } function toStr(obj) { return objectToString.call(obj); } function nameOf(f) { if (f.name) { return f.name; } var m = match.call(f, /^function\s*([\w$]+)/); if (m) { return m[1]; } return null; } function indexOf(xs, x) { if (xs.indexOf) { return xs.indexOf(x); } for (var i = 0, l = xs.length; i < l; i++) { if (xs[i] === x) { return i; } } return -1; } function isMap(x) { if (!mapSize || !x || typeof x !== 'object') { return false; } try { mapSize.call(x); try { setSize.call(x); } catch (s) { return true; } return x instanceof Map; // core-js workaround, pre-v2.5.0 } catch (e) {} return false; } function isWeakMap(x) { if (!weakMapHas || !x || typeof x !== 'object') { return false; } try { weakMapHas.call(x, weakMapHas); try { weakSetHas.call(x, weakSetHas); } catch (s) { return true; } return x instanceof WeakMap; // core-js workaround, pre-v2.5.0 } catch (e) {} return false; } function isSet(x) { if (!setSize || !x || typeof x !== 'object') { return false; } try { setSize.call(x); try { mapSize.call(x); } catch (m) { return true; } return x instanceof Set; // core-js workaround, pre-v2.5.0 } catch (e) {} return false; } function isWeakSet(x) { if (!weakSetHas || !x || typeof x !== 'object') { return false; } try { weakSetHas.call(x, weakSetHas); try { weakMapHas.call(x, weakMapHas); } catch (s) { return true; } return x instanceof WeakSet; // core-js workaround, pre-v2.5.0 } catch (e) {} return false; } function isElement(x) { if (!x || typeof x !== 'object') { return false; } if (typeof HTMLElement !== 'undefined' && x instanceof HTMLElement) { return true; } return typeof x.nodeName === 'string' && typeof x.getAttribute === 'function'; } function inspectString(str, opts) { // eslint-disable-next-line no-control-regex var s = str.replace(/(['\\])/g, '\\$1').replace(/[\x00-\x1f]/g, lowbyte); return wrapQuotes(s, 'single', opts); } function lowbyte(c) { var n = c.charCodeAt(0); var x = { 8: 'b', 9: 't', 10: 'n', 12: 'f', 13: 'r' }[n]; if (x) { return '\\' + x; } return '\\x' + (n < 0x10 ? '0' : '') + n.toString(16); } function markBoxed(str) { return 'Object(' + str + ')'; } function weakCollectionOf(type) { return type + ' { ? }'; } function collectionOf(type, size, entries) { return type + ' (' + size + ') {' + entries.join(', ') + '}'; } function arrObjKeys(obj, inspect) { var isArr = isArray(obj); var xs = []; if (isArr) { xs.length = obj.length; for (var i = 0; i < obj.length; i++) { xs[i] = has(obj, i) ? inspect(obj[i], obj) : ''; } } for (var key in obj) { // eslint-disable-line no-restricted-syntax if (!has(obj, key)) { continue; } // eslint-disable-line no-restricted-syntax, no-continue if (isArr && String(Number(key)) === key && key < obj.length) { continue; } // eslint-disable-line no-restricted-syntax, no-continue if ((/[^\w$]/).test(key)) { xs.push(inspect(key, obj) + ': ' + inspect(obj[key], obj)); } else { xs.push(key + ': ' + inspect(obj[key], obj)); } } return xs; } /***/ }), /* 118 */ /***/ (function(module, exports) { /* (ignored) */ /***/ }), /* 119 */ /***/ (function(module, exports) { // Unique ID creation requires a high quality random # generator. In the // browser this is a little complicated due to unknown quality of Math.random() // and inconsistent support for the `crypto` API. We do the best we can via // feature-detection // getRandomValues needs to be invoked in a context where "this" is a Crypto // implementation. Also, find the complete implementation of crypto on IE11. var getRandomValues = (typeof(crypto) != 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto)) || (typeof(msCrypto) != 'undefined' && typeof window.msCrypto.getRandomValues == 'function' && msCrypto.getRandomValues.bind(msCrypto)); if (getRandomValues) { // WHATWG crypto RNG - http://wiki.whatwg.org/wiki/Crypto var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef module.exports = function whatwgRNG() { getRandomValues(rnds8); return rnds8; }; } else { // Math.random()-based (RNG) // // If all else fails, use Math.random(). It's fast, but is of unspecified // quality. var rnds = new Array(16); module.exports = function mathRNG() { for (var i = 0, r; i < 16; i++) { if ((i & 0x03) === 0) r = Math.random() * 0x100000000; rnds[i] = r >>> ((i & 0x03) << 3) & 0xff; } return rnds; }; } /***/ }), /* 120 */ /***/ (function(module, exports) { /** * Convert array of 16 byte values to UUID string format of the form: * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX */ var byteToHex = []; for (var i = 0; i < 256; ++i) { byteToHex[i] = (i + 0x100).toString(16).substr(1); } function bytesToUuid(buf, offset) { var i = offset || 0; var bth = byteToHex; // join used to fix memory issue caused by concatenation: https://bugs.chromium.org/p/v8/issues/detail?id=3175#c4 return ([ bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], '-', bth[buf[i++]], bth[buf[i++]], '-', bth[buf[i++]], bth[buf[i++]], '-', bth[buf[i++]], bth[buf[i++]], '-', bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]] ]).join(''); } module.exports = bytesToUuid; /***/ }), /* 121 */ /***/ (function(module, exports) { function _extends() { module.exports = _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } module.exports = _extends; /***/ }), /* 122 */ /***/ (function(module, exports) { function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } } module.exports = _arrayWithoutHoles; /***/ }), /* 123 */ /***/ (function(module, exports) { function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } module.exports = _iterableToArray; /***/ }), /* 124 */ /***/ (function(module, exports) { function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } module.exports = _nonIterableSpread; /***/ }), /* 125 */ /***/ (function(module, exports, __webpack_require__) { var content = __webpack_require__(126); if (typeof content === 'string') { content = [[module.i, content, '']]; } var options = {} options.insert = "head"; options.singleton = false; var update = __webpack_require__(128)(content, options); if (content.locals) { module.exports = content.locals; } /***/ }), /* 126 */ /***/ (function(module, exports, __webpack_require__) { exports = module.exports = __webpack_require__(127)(false); // Module exports.push([module.i, ".ReactTable{position:relative;display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-orient:vertical;-webkit-box-direction:normal;-ms-flex-direction:column;flex-direction:column;border:1px solid rgba(0,0,0,0.1)}.ReactTable *{box-sizing:border-box}.ReactTable .rt-table{-webkit-box-flex:1;-ms-flex:auto 1;flex:auto 1;display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-orient:vertical;-webkit-box-direction:normal;-ms-flex-direction:column;flex-direction:column;-webkit-box-align:stretch;-ms-flex-align:stretch;align-items:stretch;width:100%;border-collapse:collapse;overflow:auto}.ReactTable .rt-thead{-webkit-box-flex:1;-ms-flex:1 0 auto;flex:1 0 auto;display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-orient:vertical;-webkit-box-direction:normal;-ms-flex-direction:column;flex-direction:column;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.ReactTable .rt-thead.-headerGroups{background:rgba(0,0,0,0.03);border-bottom:1px solid rgba(0,0,0,0.05)}.ReactTable .rt-thead.-filters{border-bottom:1px solid rgba(0,0,0,0.05)}.ReactTable .rt-thead.-filters input,.ReactTable .rt-thead.-filters select{border:1px solid rgba(0,0,0,0.1);background:#fff;padding:5px 7px;font-size:inherit;border-radius:3px;font-weight:normal;outline-width:0}.ReactTable .rt-thead.-filters .rt-th{border-right:1px solid rgba(0,0,0,0.02)}.ReactTable .rt-thead.-header{box-shadow:0 2px 15px 0 rgba(0,0,0,0.15)}.ReactTable .rt-thead .rt-tr{text-align:center}.ReactTable .rt-thead .rt-th,.ReactTable .rt-thead .rt-td{padding:5px 5px;line-height:normal;position:relative;border-right:1px solid rgba(0,0,0,0.05);transition:box-shadow 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275);box-shadow:inset 0 0 0 0 transparent}.ReactTable .rt-thead .rt-th.-sort-asc,.ReactTable .rt-thead .rt-td.-sort-asc{box-shadow:inset 0 3px 0 0 rgba(0,0,0,0.6)}.ReactTable .rt-thead .rt-th.-sort-desc,.ReactTable .rt-thead .rt-td.-sort-desc{box-shadow:inset 0 -3px 0 0 rgba(0,0,0,0.6)}.ReactTable .rt-thead .rt-th.-cursor-pointer,.ReactTable .rt-thead .rt-td.-cursor-pointer{cursor:pointer}.ReactTable .rt-thead .rt-th:last-child,.ReactTable .rt-thead .rt-td:last-child{border-right:0}.ReactTable .rt-thead .rt-th:focus{outline-width:0}.ReactTable .rt-thead .rt-resizable-header{overflow:visible}.ReactTable .rt-thead .rt-resizable-header:last-child{overflow:hidden}.ReactTable .rt-thead .rt-resizable-header-content{overflow:hidden;text-overflow:ellipsis}.ReactTable .rt-thead .rt-header-pivot{border-right-color:#f7f7f7}.ReactTable .rt-thead .rt-header-pivot:after,.ReactTable .rt-thead .rt-header-pivot:before{left:100%;top:50%;border:solid transparent;content:\" \";height:0;width:0;position:absolute;pointer-events:none}.ReactTable .rt-thead .rt-header-pivot:after{border-color:rgba(255,255,255,0);border-left-color:#fff;border-width:8px;margin-top:-8px}.ReactTable .rt-thead .rt-header-pivot:before{border-color:rgba(102,102,102,0);border-left-color:#f7f7f7;border-width:10px;margin-top:-10px}.ReactTable .rt-tbody{-webkit-box-flex:99999;-ms-flex:99999 1 auto;flex:99999 1 auto;display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-orient:vertical;-webkit-box-direction:normal;-ms-flex-direction:column;flex-direction:column;overflow:auto}.ReactTable .rt-tbody .rt-tr-group{border-bottom:solid 1px rgba(0,0,0,0.05)}.ReactTable .rt-tbody .rt-tr-group:last-child{border-bottom:0}.ReactTable .rt-tbody .rt-td{border-right:1px solid rgba(0,0,0,0.02)}.ReactTable .rt-tbody .rt-td:last-child{border-right:0}.ReactTable .rt-tbody .rt-expandable{cursor:pointer;text-overflow:clip}.ReactTable .rt-tr-group{-webkit-box-flex:1;-ms-flex:1 0 auto;flex:1 0 auto;display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-orient:vertical;-webkit-box-direction:normal;-ms-flex-direction:column;flex-direction:column;-webkit-box-align:stretch;-ms-flex-align:stretch;align-items:stretch}.ReactTable .rt-tr{-webkit-box-flex:1;-ms-flex:1 0 auto;flex:1 0 auto;display:-webkit-inline-box;display:-ms-inline-flexbox;display:inline-flex}.ReactTable .rt-th,.ReactTable .rt-td{-webkit-box-flex:1;-ms-flex:1 0 0px;flex:1 0 0;white-space:nowrap;text-overflow:ellipsis;padding:7px 5px;overflow:hidden;transition:.3s ease;transition-property:width,min-width,padding,opacity}.ReactTable .rt-th.-hidden,.ReactTable .rt-td.-hidden{width:0 !important;min-width:0 !important;padding:0 !important;border:0 !important;opacity:0 !important}.ReactTable .rt-expander{display:inline-block;position:relative;margin:0;color:transparent;margin:0 10px}.ReactTable .rt-expander:after{content:'';position:absolute;width:0;height:0;top:50%;left:50%;-webkit-transform:translate(-50%, -50%) rotate(-90deg);transform:translate(-50%, -50%) rotate(-90deg);border-left:5.04px solid transparent;border-right:5.04px solid transparent;border-top:7px solid rgba(0,0,0,0.8);transition:all 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275);cursor:pointer}.ReactTable .rt-expander.-open:after{-webkit-transform:translate(-50%, -50%) rotate(0);transform:translate(-50%, -50%) rotate(0)}.ReactTable .rt-resizer{display:inline-block;position:absolute;width:36px;top:0;bottom:0;right:-18px;cursor:col-resize;z-index:10}.ReactTable .rt-tfoot{-webkit-box-flex:1;-ms-flex:1 0 auto;flex:1 0 auto;display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-orient:vertical;-webkit-box-direction:normal;-ms-flex-direction:column;flex-direction:column;box-shadow:0 0 15px 0 rgba(0,0,0,0.15)}.ReactTable .rt-tfoot .rt-td{border-right:1px solid rgba(0,0,0,0.05)}.ReactTable .rt-tfoot .rt-td:last-child{border-right:0}.ReactTable.-striped .rt-tr.-odd{background:rgba(0,0,0,0.03)}.ReactTable.-highlight .rt-tbody .rt-tr:not(.-padRow):hover{background:rgba(0,0,0,0.05)}.ReactTable .-pagination{z-index:1;display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-pack:justify;-ms-flex-pack:justify;justify-content:space-between;-webkit-box-align:stretch;-ms-flex-align:stretch;align-items:stretch;-ms-flex-wrap:wrap;flex-wrap:wrap;padding:3px;box-shadow:0 0 15px 0 rgba(0,0,0,0.1);border-top:2px solid rgba(0,0,0,0.1)}.ReactTable .-pagination input,.ReactTable .-pagination select{border:1px solid rgba(0,0,0,0.1);background:#fff;padding:5px 7px;font-size:inherit;border-radius:3px;font-weight:normal;outline-width:0}.ReactTable .-pagination .-btn{-webkit-appearance:none;-moz-appearance:none;appearance:none;display:block;width:100%;height:100%;border:0;border-radius:3px;padding:6px;font-size:1em;color:rgba(0,0,0,0.6);background:rgba(0,0,0,0.1);transition:all .1s ease;cursor:pointer;outline-width:0}.ReactTable .-pagination .-btn[disabled]{opacity:.5;cursor:default}.ReactTable .-pagination .-btn:not([disabled]):hover{background:rgba(0,0,0,0.3);color:#fff}.ReactTable .-pagination .-previous,.ReactTable .-pagination .-next{-webkit-box-flex:1;-ms-flex:1;flex:1;text-align:center}.ReactTable .-pagination .-center{-webkit-box-flex:1.5;-ms-flex:1.5;flex:1.5;text-align:center;margin-bottom:0;display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-orient:horizontal;-webkit-box-direction:normal;-ms-flex-direction:row;flex-direction:row;-ms-flex-wrap:wrap;flex-wrap:wrap;-webkit-box-align:center;-ms-flex-align:center;align-items:center;-ms-flex-pack:distribute;justify-content:space-around}.ReactTable .-pagination .-pageInfo{display:inline-block;margin:3px 10px;white-space:nowrap}.ReactTable .-pagination .-pageJump{display:inline-block}.ReactTable .-pagination .-pageJump input{width:70px;text-align:center}.ReactTable .-pagination .-pageSizeOptions{margin:3px 10px}.ReactTable .rt-noData{display:block;position:absolute;left:50%;top:50%;-webkit-transform:translate(-50%, -50%);transform:translate(-50%, -50%);background:rgba(255,255,255,0.8);transition:all .3s ease;z-index:1;pointer-events:none;padding:20px;color:rgba(0,0,0,0.5)}.ReactTable .-loading{display:block;position:absolute;left:0;right:0;top:0;bottom:0;background:rgba(255,255,255,0.8);transition:all .3s ease;z-index:-1;opacity:0;pointer-events:none}.ReactTable .-loading>div{position:absolute;display:block;text-align:center;width:100%;top:50%;left:0;font-size:15px;color:rgba(0,0,0,0.6);-webkit-transform:translateY(-52%);transform:translateY(-52%);transition:all 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94)}.ReactTable .-loading.-active{opacity:1;z-index:2;pointer-events:all}.ReactTable .-loading.-active>div{-webkit-transform:translateY(50%);transform:translateY(50%)}.ReactTable .rt-resizing .rt-th,.ReactTable .rt-resizing .rt-td{transition:none !important;cursor:col-resize;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}\n", ""]); /***/ }), /* 127 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ // css base code, injected by the css-loader // eslint-disable-next-line func-names module.exports = function (useSourceMap) { var list = []; // return the list of modules as css string list.toString = function toString() { return this.map(function (item) { var content = cssWithMappingToString(item, useSourceMap); if (item[2]) { return "@media ".concat(item[2], "{").concat(content, "}"); } return content; }).join(''); }; // import a list of modules into the list // eslint-disable-next-line func-names list.i = function (modules, mediaQuery) { if (typeof modules === 'string') { // eslint-disable-next-line no-param-reassign modules = [[null, modules, '']]; } var alreadyImportedModules = {}; for (var i = 0; i < this.length; i++) { // eslint-disable-next-line prefer-destructuring var id = this[i][0]; if (id != null) { alreadyImportedModules[id] = true; } } for (var _i = 0; _i < modules.length; _i++) { var item = modules[_i]; // skip already imported module // this implementation is not 100% perfect for weird media query combinations // when a module is imported multiple times with different media queries. // I hope this will never occur (Hey this way we have smaller bundles) if (item[0] == null || !alreadyImportedModules[item[0]]) { if (mediaQuery && !item[2]) { item[2] = mediaQuery; } else if (mediaQuery) { item[2] = "(".concat(item[2], ") and (").concat(mediaQuery, ")"); } list.push(item); } } }; return list; }; function cssWithMappingToString(item, useSourceMap) { var content = item[1] || ''; // eslint-disable-next-line prefer-destructuring var cssMapping = item[3]; if (!cssMapping) { return content; } if (useSourceMap && typeof btoa === 'function') { var sourceMapping = toComment(cssMapping); var sourceURLs = cssMapping.sources.map(function (source) { return "/*# sourceURL=".concat(cssMapping.sourceRoot).concat(source, " */"); }); return [content].concat(sourceURLs).concat([sourceMapping]).join('\n'); } return [content].join('\n'); } // Adapted from convert-source-map (MIT) function toComment(sourceMap) { // eslint-disable-next-line no-undef var base64 = btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap)))); var data = "sourceMappingURL=data:application/json;charset=utf-8;base64,".concat(base64); return "/*# ".concat(data, " */"); } /***/ }), /* 128 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var stylesInDom = {}; var isOldIE = function isOldIE() { var memo; return function memorize() { if (typeof memo === 'undefined') { // Test for IE <= 9 as proposed by Browserhacks // @see http://browserhacks.com/#hack-e71d8692f65334173fee715c222cb805 // Tests for existence of standard globals is to allow style-loader // to operate correctly into non-standard environments // @see https://github.com/webpack-contrib/style-loader/issues/177 memo = Boolean(window && document && document.all && !window.atob); } return memo; }; }(); var getTarget = function getTarget() { var memo = {}; return function memorize(target) { if (typeof memo[target] === 'undefined') { var styleTarget = document.querySelector(target); // Special case to return head of iframe instead of iframe itself if (window.HTMLIFrameElement && styleTarget instanceof window.HTMLIFrameElement) { try { // This will throw an exception if access to iframe is blocked // due to cross-origin restrictions styleTarget = styleTarget.contentDocument.head; } catch (e) { // istanbul ignore next styleTarget = null; } } memo[target] = styleTarget; } return memo[target]; }; }(); function listToStyles(list, options) { var styles = []; var newStyles = {}; for (var i = 0; i < list.length; i++) { var item = list[i]; var id = options.base ? item[0] + options.base : item[0]; var css = item[1]; var media = item[2]; var sourceMap = item[3]; var part = { css: css, media: media, sourceMap: sourceMap }; if (!newStyles[id]) { styles.push(newStyles[id] = { id: id, parts: [part] }); } else { newStyles[id].parts.push(part); } } return styles; } function addStylesToDom(styles, options) { for (var i = 0; i < styles.length; i++) { var item = styles[i]; var domStyle = stylesInDom[item.id]; var j = 0; if (domStyle) { domStyle.refs++; for (; j < domStyle.parts.length; j++) { domStyle.parts[j](item.parts[j]); } for (; j < item.parts.length; j++) { domStyle.parts.push(addStyle(item.parts[j], options)); } } else { var parts = []; for (; j < item.parts.length; j++) { parts.push(addStyle(item.parts[j], options)); } stylesInDom[item.id] = { id: item.id, refs: 1, parts: parts }; } } } function insertStyleElement(options) { var style = document.createElement('style'); if (typeof options.attributes.nonce === 'undefined') { var nonce = true ? __webpack_require__.nc : undefined; if (nonce) { options.attributes.nonce = nonce; } } Object.keys(options.attributes).forEach(function (key) { style.setAttribute(key, options.attributes[key]); }); if (typeof options.insert === 'function') { options.insert(style); } else { var target = getTarget(options.insert || 'head'); if (!target) { throw new Error("Couldn't find a style target. This probably means that the value for the 'insert' parameter is invalid."); } target.appendChild(style); } return style; } function removeStyleElement(style) { // istanbul ignore if if (style.parentNode === null) { return false; } style.parentNode.removeChild(style); } /* istanbul ignore next */ var replaceText = function replaceText() { var textStore = []; return function replace(index, replacement) { textStore[index] = replacement; return textStore.filter(Boolean).join('\n'); }; }(); function applyToSingletonTag(style, index, remove, obj) { var css = remove ? '' : obj.css; // For old IE /* istanbul ignore if */ if (style.styleSheet) { style.styleSheet.cssText = replaceText(index, css); } else { var cssNode = document.createTextNode(css); var childNodes = style.childNodes; if (childNodes[index]) { style.removeChild(childNodes[index]); } if (childNodes.length) { style.insertBefore(cssNode, childNodes[index]); } else { style.appendChild(cssNode); } } } function applyToTag(style, options, obj) { var css = obj.css; var media = obj.media; var sourceMap = obj.sourceMap; if (media) { style.setAttribute('media', media); } if (sourceMap && btoa) { css += "\n/*# sourceMappingURL=data:application/json;base64,".concat(btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap)))), " */"); } // For old IE /* istanbul ignore if */ if (style.styleSheet) { style.styleSheet.cssText = css; } else { while (style.firstChild) { style.removeChild(style.firstChild); } style.appendChild(document.createTextNode(css)); } } var singleton = null; var singletonCounter = 0; function addStyle(obj, options) { var style; var update; var remove; if (options.singleton) { var styleIndex = singletonCounter++; style = singleton || (singleton = insertStyleElement(options)); update = applyToSingletonTag.bind(null, style, styleIndex, false); remove = applyToSingletonTag.bind(null, style, styleIndex, true); } else { style = insertStyleElement(options); update = applyToTag.bind(null, style, options); remove = function remove() { removeStyleElement(style); }; } update(obj); return function updateStyle(newObj) { if (newObj) { if (newObj.css === obj.css && newObj.media === obj.media && newObj.sourceMap === obj.sourceMap) { return; } update(obj = newObj); } else { remove(); } }; } module.exports = function (list, options) { options = options || {}; options.attributes = typeof options.attributes === 'object' ? options.attributes : {}; // Force single-tag solution on IE6-9, which has a hard limit on the # of